我需要读入一个整数列表并将它们存储在一个数组中。整数的数量是未知的,因此如果数组变满并且有更多整数要读入,则需要调整数组的大小。它们只会被读入一次,程序会知道用户在输入某个特定值时已完成输入终止循环的值。
无论如何,我意识到我将使用 malloc() 和 realloc() 但有点困惑。我们将使用 scanf() 来读取值。
假设我最初创建的数组大小为 10。我想我会在循环中使用 if/else 语句来确定何时使用 realloc,但我不确定如何检查它。
int value;
int index;
int* myArray;
// Allocate space for array of 10 ints to start
myArray = malloc(sizeof(int)*SIZE);
index = 0;
// Prompt
printf("Please enter as many integers as you would like.\n");
printf("Enter the integer '123' to indicate when you are finished.\n\n");
scanf("%d", &value);
while (value != 123) {
scanf("%d", &value);
myArray[index] = value;
index++;
}
我认为这会正确读取整数并将它们存储在 myArray 中。现在,当它达到第 10 个 int 时,每次达到限制时我都想将数组大小加倍,依此类推,对吗?
最佳答案
首先,您忽略了第一个整数。循环体应该在等待下一个整数之前写入数组,如下所示:
scanf("%d", &value);
while (value != 123) {
myArray[index] = value;
index++;
scanf("%d", &value);
}
现在,您需要保留一个变量来保存当前数组的大小。然后,在写入数组之前,如果索引等于当前数组的大小,则需要重新分配:
arr_sz = SIZE;
scanf("%d", &value);
while (value != 123) {
if (index == arr_sz) {
arr_sz *= 2;
myArray = realloc(myArray, sizeof(*myArray)*arr_sz);
}
myArray[index] = value;
index++;
scanf("%d", &value);
}
您可能想要测试并确保 malloc()
和 realloc()
不会返回 NULL
。
在最后的旁注中,我建议您更改第一个分配:
myArray = malloc(sizeof(int)*SIZE);
稍微更易于维护的形式:
myArray = malloc(sizeof(*myArray)*SIZE);
这样,即使myArray
的类型发生变化,也不需要更新这行代码。
关于c - 无法理解如何在 C 中调整动态数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28223038/