为链表创建全局结构变量时,它说非法初始化,否则它工作正常
When creating global struct variable for linked list it says illegal initialization otherwise it works fine
我已经创建了这个结构,我正在尝试借助我创建的函数来执行基本操作。我的程序可以运行,但我必须在每个函数中声明 temp
变量。我试着让它成为全球性的,但它说“非法初始化”。
struct node
{
int data;
struct node* next;
};
struct node* head=NULL;
struct node* temp=(struct node*)malloc(sizeof(struct node));
//If I remove the above line and move it to the disp function it works
//but in this case it says illegal initialization
void disp()
{
temp=head;
while(temp!=NULL)
{
printf(" %d ",temp->data);
temp=temp->next;
}
}
我应该将整个程序添加到这段代码中吗?
在C语言中,全局变量是由编译器初始化的,因此它必须是常量值,比如第一行的NULL。但是在您的情况下,您正在尝试调用一个不允许的函数 (malloc())。
来源:https://www.geeksforgeeks.org/initialization-global-static-variables-c/
我已经创建了这个结构,我正在尝试借助我创建的函数来执行基本操作。我的程序可以运行,但我必须在每个函数中声明 temp
变量。我试着让它成为全球性的,但它说“非法初始化”。
struct node
{
int data;
struct node* next;
};
struct node* head=NULL;
struct node* temp=(struct node*)malloc(sizeof(struct node));
//If I remove the above line and move it to the disp function it works
//but in this case it says illegal initialization
void disp()
{
temp=head;
while(temp!=NULL)
{
printf(" %d ",temp->data);
temp=temp->next;
}
}
我应该将整个程序添加到这段代码中吗?
在C语言中,全局变量是由编译器初始化的,因此它必须是常量值,比如第一行的NULL。但是在您的情况下,您正在尝试调用一个不允许的函数 (malloc())。
来源:https://www.geeksforgeeks.org/initialization-global-static-variables-c/