c - 读取输入(int)并使用 malloc 和 realloc 将其存储到数组中

标签 c int malloc realloc

我正在尝试从标准输入读取整数,但我不知道长度。我试过了,但我不知道为什么它不起作用

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *arr = (int *) malloc(sizeof(int));


    int sizeCounter = 0;
    int tmp = 0;
    while(scanf("%d", &tmp) != EOF)
    {   

        arr = (int *) realloc(arr, sizeof(arr)+sizeof(int));
        arr[sizeCounter] = tmp;     
        sizeCounter++;          

    }
}

错误 - realloc():无效指针:0xb76d8000 *

最佳答案

这一行是错误的。

    arr = (int *) realloc(arr, sizeof(arr)+sizeof(int));

sizeof(arr)+sizeof(int) 是一个常量。它等于 sizeof(int*)+sizeof(int)

你需要的是:

    arr = (int *) realloc(arr, (sizeCounter+1)*sizeof(int));

关于c - 读取输入(int)并使用 malloc 和 realloc 将其存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23642413/

相关文章:

c - 写入偶数和奇数的程序

我可以用 popen() 解析 ngrep 的输出吗?

c++ - 如何有效地在 std::vector 中插入一对?

c++ - 在 C/C++ 共享内存中等待和通知

c - 在 C 中的输入系统调用期间添加的额外字符串

java - 如何将 Int 转换为无符号字节并返回

PHP int 到唯一的 rgb 颜色

c - C中的指针的自由函数如何工作?

c++ - 将指针传递给函数并使用 realloc

c - 我怎样才能在c中创建一个n维数组