为链表创建全局结构变量时,它表示非法初始化,否则工作正常

时间:2018-12-07 04:30:05

标签: c linked-list singly-linked-list

我已经创建了此结构,并且尝试在所创建的功能的帮助下执行基本操作。我的程序可以运行,但是我必须在每个函数中声明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;
    }
}

我应该将整个程序添加到此代码中吗?

1 个答案:

答案 0 :(得分:2)

在C中,全局变量由编译器初始化,因此它必须是一个常量值,例如第一行中的NULL。但是在您的情况下,您试图调用不允许的函数(malloc())。

来源:https://www.geeksforgeeks.org/initialization-global-static-variables-c/