我必须写一个程序,从内存中存储和打印整数。我必须使用realloc。基本上,程序为2个int分配大小。当输入被赋予2个整数时,它应该为1个整数重新分配空间并打印出双整数。接下来,当输入被赋予3个int时,它应该为int再分配2个空格,并输出double。。等等。。

Test cases:

input file in.0:
------
4
------

expected output:
------
4
------

=================================================

input file in.1:
------
4 5
------

expected output:
------
4
5
double
------

==================================================

input file in.2:
------
4 5 3
------

expected output:
------
4
5
double
3
double
------

===================================================

input file in.3:
------
4 5 3 2 9
------

expected output:
------
4
5
double
3
double
2
9
double

我写了这个程序,但它没有正确分配内存。有人能指引我写作方向吗?
int main(void)
{
    int c;

    int digit;
    int count = 0;
    int d_size = 1;
    int init_size = 2;
    int *p = (int *) malloc(sizeof(int) * init_size);

    while((c = scanf("%i", &digit)) != EOF)
    {
        if (c == 1)
        {
            *(p+count) = digit;
            count++;
        }
        else
        {
            printf("not valid");
        }

        printf("%i\n", digit);

        if (count >= 2)
        {
            printf("double\n");
            p = (int *) realloc(p, sizeof(int) * d_size);
            d_size = d_size * 2;
        }

    }

最佳答案

你的init_size是2,但你的d_size是1。首先,使d_size等于init_size。其次,您需要在d_size = d_size * 2之前执行realloc操作,以便实际增大大小。
旁注:如果内存不足,realloc将失败。如果你写:

p = realloc(p, ...);

如果失败,您将丢失以前分配的内存。您应该始终像这样使用realloc
enlarged = realloc(p, ...);
if (enlarged == NULL)
    // handle error
else
    p = enlarged;

旁注2:你可能会改变指针的类型。最好不要重复。而不是
int *p;
p = (int *)malloc(sizeof(int) * count);

写入:
int *p;
p = malloc(sizeof(*p) * count);

关于c - C编程:如何在此程序中使用realloc?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11233080/

10-11 22:13
查看更多