Error "initializer element is not constant" when allocate the memory

Ang*_*gus 5 c

  1 #include<stdio.h>
  2 #include<malloc.h>
  3 
  4 typedef struct node_t{
  5     int i;
  6     struct node_t* link;
  7 }node;
  8 
  9 node* head = (node *)malloc(sizeof(node));
 10 
 11 if(head == NULL){
 12     printf("\n malloc for head node failed! \n");
 13 }
 14 
 15 int main(){
 16     int i = 10;
 17     node* temp = NULL;
 18     temp = (node *)malloc(sizeof(node));
 19     if(temp == NULL){
 20         printf("\n malloc for temp node failed! \n");
 21     }
 22     else{
 23         while(i<=10){
 24             ;
 25         }
 26     }
 27     return 0;
 28 } 
Run Code Online (Sandbox Code Playgroud)

compilation error:

linked.c:9:1: error: initializer element is not constant
linked.c:11:1: error: expected identifier or ‘(’ before ‘if’
Run Code Online (Sandbox Code Playgroud)

I'm trying a simple linked list programme. It's not fully completed. I'm getting a compilation error. Couldn't understand why this happened.

Jer*_*fin 8

由于您将其定义head为全局,因此其初始化程序需要是常量 - 基本上,编译器/链接器应该能够在可执行文件中为其分配空间,将初始化程序写入空间,然后完成.malloc在初始化过程中没有像上面那样进行调用的规定- 你需要在内部main(或者你调用的内容main)中进行调用.

#include <stdlib.h>

void init() { 
    head = malloc(sizeof(node));
}

int main() { 
    init();
    // ...
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您拥有的代码main从未实际使用过head,因此您可以跳过上述所有内容而不会出现问题.


Omk*_*ant 7

 9  node* head = (node *)malloc(sizeof(node));
 10 
 11 if(head == NULL){
 12     printf("\n malloc for head node failed! \n");
 13 }
Run Code Online (Sandbox Code Playgroud)

这些行在外部是不可能的,main()因为任何函数调用或可执行文件都应该在main()函数内部或从main调用的任何函数中.

对于 linked.c:9:1: error: initializer element is not constant

只有函数定义或任何全局初始化才可能在外部,main()但初始化程序必须是常量表达式 `.

您可以声明head为全局但初始化是错误的.

像这样做 :

node * head =NULL // here initialization using constant expression


void function () // any function 
{
 head = malloc(sizeof(node));
}
Run Code Online (Sandbox Code Playgroud)

对于linked.c:11:1: error: expected identifier,

if声明不能超出任何功能.在您的情况下,将这些行放在main中并解决问题