Mic*_*arn 1 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; }
}
Run Code Online (Sandbox Code Playgroud)
警告信息:
|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 ===|
Run Code Online (Sandbox Code Playgroud)
结果编译要求5个整数并打印"添加更多空间...",此时程序终止,而不是要求额外的三个整数并打印输入.
你能帮忙的话,我会很高兴.:) 谢谢!
你没有realloc
按照你应该的方式使用:
/* 8 is not valid here. You need to pass the previous pointer. */
arr = realloc(8, sizeof(int));
Run Code Online (Sandbox Code Playgroud)
尝试:
tmp = realloc(arr, 8 * sizeof(*arr));
if (NULL != tmp)
arr = tmp;
Run Code Online (Sandbox Code Playgroud)
顺便说一句,你的程序看起来很麻烦,这使得它很难阅读.也许偶尔会留空线?
归档时间: |
|
查看次数: |
2356 次 |
最近记录: |