c中带有终止符的动态数组

Dynamic array in c with terminator character

我想编写一个程序,在内存中分配一个动态数组,并让它一直监听输入,直到值“-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;
    }
}