#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");
}
#include <stdlib.h>
以获得对malloc()
的正确声明(如果没有它,你的“工作”代码在大多数64位系统上都会有错误)。 - Michael Burr