gpt4 book ai didi

c - 如何在 C 函数中返回 `realloc` 数组

转载 作者:太空宇宙 更新时间:2023-11-04 06:51:40 25 4
gpt4 key购买 nike

我想将数字附加到一个空数组中,而这些数字的数量在开始时是未知的。例如,生成从 1 到 10 的数字并一个接一个地追加。

generateFromOneToTen 会将我的结果保存在 output 中,执行后 count 应该是 10。如果我在此函数中打印结果,一切都很好。

int generateFromOneToTen(int *output, int count)
{
for (int i = 0; i < 10; i++) {
output = arrayAppendInt(output, i + 1, count);
count++;
}

// Print result of `output` is 1,2,3...10 here

return count;
}

我还实现了 arrayAppendInt 以动态增加数组的长度并在旧值之后附加新值。

int *arrayAppendInt(int *array, int value, int size) 
{
int newSize = size + 1;
int *newArray = (int*) realloc(array, newSize * sizeof(int));

if (newArray == NULL) {
printf("ERROR: unable to realloc memory \n");
return NULL;
}

newArray[size] = value;

return newArray;
}

问题来了。调用生成函数时,numbers 将始终为 NULL。如何将生成的数字返回给 numbers 变量?

int *numbers = NULL;
int count = 0;
count = generateFromOneToTen(numbers, 0);
^^^^^^^

最佳答案

您可以使用指向整数指针的指针 (int **):

int generateFromOneToTen(int **output, int count)
{
for (int i = 0; i < 10; i++) {
*output = arrayAppendInt(*output, i + 1, count);
count++;
}
// `*output` is 1,2,3...10 here
return count;
}

您可以像这样重写 arrayAppendInt 函数:

int *arrayAppendInt(int *array, int value, int size) 
{
int newSize = size + 1;
int *newArray;
if (array==NULL)
newArray = (int*) malloc ((1+size) * sizeof(int));
else
newArray = (int*) realloc(array, newSize * sizeof(int));

if (newArray == NULL) {
printf("ERROR: unable to realloc memory \n");
return NULL;
}

newArray[size] = value;

return newArray;
}

然后这样调用它 *output = arrayAppendInt(*output, i + 1, i);

关于c - 如何在 C 函数中返回 `realloc` 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50269236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com