c - 无法使用 realloc : "invalid next size" 扩展数组

标签 c arrays realloc

我似乎无法使用 realloc 扩展数组...请帮帮我 这是代码:

main() 
{
    int resultarray[] = {1},  i = 0 ,ch ;
    int *number = malloc(sizeof(int));

    printf("Enter number : ");

    while ( ch = getchar() != '\n' ) {
        number[i++] = ch-48 ;
        number = realloc(number,sizeof(int));
    }
    printf("%d",i);
}

* Error in `./a.out': realloc(): invalid next size: 0x0000000002083010 *

最佳答案

您的代码根本不会扩大数组(因此写得超出 分配的内存,这可能会导致各种未定义的丑陋行为)。

你的意思可能是这样的

number = realloc(number,(i+1)*sizeof(int));

realloc() 的第二个参数是 大小,而不是附加 大小。

关于c - 无法使用 realloc : "invalid next size" 扩展数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21563313/

相关文章:

c - MSVC : "too few arguments in function call" when omitting optional parameter

c - 从c中的fread()形式读取缓冲区数据

python - 如何在 Python 中将二进制向量旋转到最小值

c - 与枚举器同名的变量

c - 如何正确调整位图的大小?

javascript - 数组名实例数组;没有按预期工作

c - 在 C 中分配动态结构数组

c - 当我试图用 C 读取文件时,为什么 fscanf 会随机更改字符串中的字符?

c - Realloc:结构动态 vector 中的下一个大小无效

c - TIOCM_OUT1 和 TIOCM_OUT2 有什么用?