首页 文章

C编程:如何在此程序中使用realloc?

提问于
浏览
0

我必须编写一个程序来存储和打印内存中的整数 . 我必须使用realloc . 基本上,程序分配2个整数的大小 . 当输入给出2个整数时,它应该重新分配1个int的空间并打印出double . 接下来,当输入给出3个整数时,它应该为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;
        }

    }

1 回答

  • 4

    你的 init_size 是2,但你的 d_size 是1.首先,让 d_size 等于 init_size . 其次,您需要在 realloc 之前执行 d_size = d_size * 2 ,这样您实际上会增加大小 .


    旁注:如果内存不足, 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);
    

相关问题