【发布时间】:2020-12-30 13:15:24
【问题描述】:
我正在尝试创建一个动态数组,如果需要,它的大小会增加,因为我不知道该数组实际上会有多大。我的代码似乎一直有效,直到数组的第 8 个元素开始看到我没有输入的非常大的错误值。不知道为什么会这样。
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char** argv)
{
int val;
int userInput;
int* arr;
int size = 1;
int arrIndex = 0;
arr = (int*) malloc(sizeof(int) * size);
/* prompt the user for input */
printf ("Enter in a list of numbers to be stored in a dynamic array.\n");
printf ("End the list with the terminal value of -999\n");
/* loop until the user enters -999 */
scanf ("%d", &val);
while (val != -999)
{
if (arrIndex >= size)
{
size++;
}
arr[arrIndex] = val;
arrIndex++;
/* get next value */
scanf("%d", &val);
}
int j = 0;
for(j = 0; j < size ; j++)
{
printf("%d \t", arr[j]);
}
}
【问题讨论】: