Malloc函数(动态内存分配)在全局使用时导致错误

nik*_*iko 9 c malloc global-variables dynamic-memory-allocation

#include<stdio.h>
#include<string.h>
char *y;
y=(char *)malloc(40); // gives an error here
int main()
{
    strcpy(y,"hello world");
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

现在真正的问题是,我们不能在全球范围内进行动态内存分配吗?为什么在全局使用malloc时会显示错误?如果我把malloc语句放在main函数或其他函数中,代码就没有错误.为什么会这样?

#include<stdio.h>
#include<string.h>
char *y;
int main()
{
    y=(char *)malloc(40); 
    strcpy(y,"hello world");
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*Mat 22

您无法在函数之外执行代码.你可以在全局范围内做的唯一事情是声明变量(并用编译时常量初始化它们).

malloc 是函数调用,因此在函数外部无效.

如果使用mallocmain(或任何其他函数)初始化一个全局指针变量,它将可用于该变量在范围内的所有其他函数(在您的示例中,包含的文件中的所有函数main).

(请注意,应尽可能避免使用全局变量.)

  • 是的,你的第二个例子就是这样. (4认同)