【发布时间】:2011-10-08 05:46:30
【问题描述】:
#include<stdio.h>
#include<string.h>
char *y;
y=(char *)malloc(40); // gives an error here
int main()
{
strcpy(y,"hello world");
}
error: conflicting types for 'y'
error: previous declaration of 'y' was here
warning: initialization makes integer from pointer without a cast
error: initializer element is not constant
warning: data definition has no type or storage class
warning: passing arg 1 of `strcpy' makes pointer from integer without cast
现在真正的问题是,我们不能在全局范围内进行动态内存分配吗?为什么在全局使用 malloc 时会显示错误?如果我将malloc 语句放在主函数或其他函数中,代码可以正常工作。为什么会这样?
#include<stdio.h>
#include<string.h>
char *y;
int main()
{
y=(char *)malloc(40);
strcpy(y,"hello world");
}
【问题讨论】:
-
除了 Mat 的回答,别忘了
#include <stdlib.h>,这样你就可以得到malloc()的正确声明(没有它,你的“工作”代码在大多数 64 位系统上都会出错) .
标签: c malloc global-variables dynamic-memory-allocation