Initializer元素不是常量

时间:2015-10-30 21:05:54

标签: c

我正在尝试将虚拟head*声明为全局变量,但IDE正在发出此错误:

initializer element is not constant

我该如何解决?

typedef struct MyNode{
    struct MyNode *next;
    int value;
}Node;

//Declare a global variable
Node *head = malloc(sizeof(Node));
head->next = NULL;

4 个答案:

答案 0 :(得分:2)

The obvious thing to do is just to declare the head variable as a global but then do the initialisation within a function.

typedef struct MyNode{
    struct MyNode *next;
    int value;
} Node;

Node *head;

int main (int argc, char **argv)
{
    head = malloc(sizeof *head);
    if (!head) {
        /* error */
        exit(-1);
    }

    head->next = NULL;

    return 0;
}

答案 1 :(得分:1)

您无法在功能之外进行分配。 在这里您可以找到完整的讨论: Structure member assignment causing syntax error when not inside a function

答案 2 :(得分:1)

The C11 standard states in section 6.7.9 part 4:

All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals.

Your pointer head is being initialized with a function call, which is not a constant expression. The only way to initialize it with a function call is to declare it inside of a function (however, this will not work if it's declared with static due to the above restriction). Alternatively, you can just let the pointer be initialized by default to NULL, and then assign it with malloc() later on.

答案 3 :(得分:0)

来自C99标准:

  

6.7.8初始化

     

<强>约束

     

4具有静态存储持续时间的对象的初始值设定项中的所有表达式都应为常量表达式或字符串文字。

因此,

@media print

是不允许的。您可以使用常量表达式初始化Node *head = malloc(sizeof(Node)); ,例如NULL。

head

当然,声明如下:

Node *head = NULL;
外部功能不允许

。因此,必须在函数中完成head->next = NULL; 的正确初始化。一种方法是:

head