c - c中的内存分配问题

标签 c memory allocation

我即将读完 Mike McGrath 撰写的名为“简单步骤的 C 编程”的 C 编程入门书。不过,从表面上看,我认为读完这本书后我还有很多东西要学。无论如何,我正在处理内存分配并编写了这个演示程序,但是当我尝试运行它时错误关闭:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i, *arr;

    arr = calloc(5, sizeof(int));
    if(arr!=NULL)
    {
        printf("Enter 5 integers, seperated by a space:");
        for(i=0; i<5; i++) scanf("%d", &arr[i]);
        printf("Adding more space...\n");
        arr = realloc(8, sizeof(int));
        printf("Enter 3 more integers seperated by a space:");
        for(i=5; i<8; i++) scanf("%d", &arr[i]);
        printf("Thanks.\nYour 8 entries were: ");
        for(i=0; i<8; i++) printf("%d, ", arr[i]);
        printf("\n");
        free(arr);
        return 0;
        }
    else {printf("!!! INSUFFICIENT MEMORY !!!\n"); return 1; }
}

警告信息:

|13|warning: passing argument 1 of 'realloc' makes pointer from integer without a cast|
c:\program files\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.4.1\..\..\..\..\include\stdlib.h|365|note: expected 'void *' but argument is of type 'int'|
||=== Build finished: 0 errors, 1 warnings ===|

生成的编译要求 5 个整数并打印“Adding more space...”,此时程序终止,而不是要求额外的三个整数并打印输入。

任何帮助都会很好。 :) 谢谢!

最佳答案

您没有按照应有的方式使用 realloc:

/* 8 is not valid here. You need to pass the previous pointer. */
arr = realloc(8, sizeof(int));

尝试:

tmp = realloc(arr, 8 * sizeof(*arr));
if (NULL != tmp)
    arr = tmp;

顺便说一句,您的程序看起来非常拥挤,难以阅读。也许偶尔留下一个空行?

关于c - c中的内存分配问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7108978/

相关文章:

为我的结构的 char 成员赋值时出现 C 段错误

c - CUDA的__shared__内存什么时候有用?

Java实例变量的内存分配

c++ array[var][2] 作为类成员

c - C 中动态分配的字符串矩阵

c - 在 C 中通过引用将值从一个函数传递到另一个函数

c - 将 header 中的结构声明为 typedef

c - 我的数组显示 50 个元素,然后我得到随机内存大小,这是为什么?

c - 有没有办法从c中的基地址获取完整数组?

c++ - 字典的动态内存分配