我想编写一个程序,在内存中分配一个动态数组,并让它继续监听输入,直到值“-1”为止。我已经这样做了,但它占用了太多内存。
int *a=malloc(sizeof(int));
int i=0;
int j;
while (a[i-1]!=-1){
scanf("%d",a+i);
i++;
a=realloc(a,(i+2)*sizeof(int));
}
最佳答案
您没有处理输入错误。如果 scanf
无法读取,则您的程序存在未定义的行为,这可能会导致它快速耗尽您的所有内存,然后崩溃。
还建议处理realloc
失败,并且不要每次都重新分配。
将这些放在一起,并且避免将 -1 添加到数组中,它可能看起来像这样:
/* values are read into this buffer */
int size = 16, count = 0;
int *a = malloc(size * sizeof(int));
/* loop control variables */
int done = 0;
int error = 0;
/* temporary variables */
int val, new_size, *new_a;
while( !done )
{
/* double the buffer size when required */
if( count == size )
{
new_size = size * 2;
new_a = realloc(a, new_size * sizeof(*a));
if( !new_a ) {
perror("Realloc failed");
error = 1;
break;
} else {
a = new_a;
size = new_size;
}
}
/* read value and finish on input error or if user enters -1 */
if( 1 != scanf("%d", &val) || val == -1 ) {
done = 1;
} else {
a[count++] = val;
}
}
关于c - C 中带有终止符的动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40966529/