【发布时间】:2018-05-10 09:05:29
【问题描述】:
我想将数字附加到一个空数组中,而这些数字的数量在一开始是未知的。例如,生成从 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);
^^^^^^^
【问题讨论】:
-
man realloc()::
... if ptr is NULL, then the call is equivalent to malloc(size), for all values of size;... -
所以要修改函数的参数
numbers? Possible duplicate? -
最干净的解决方案是恕我直言,将数组+簿记(大小,使用)打包成一个结构,并使用(指向)这个结构的指针作为参数。