Error “initializer element is not constant” when a

2020-02-07 02:07发布

  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 } 

compilation error:

linked.c:9:1: error: initializer element is not constant
linked.c:11:1: error: expected identifier or ‘(’ before ‘if’

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.

标签: c
4条回答
We Are One
2楼-- · 2020-02-07 02:33

Since you're defining head as a global, its initializer needs to be a constant--basically, the compiler/linker should be able to allocate space for it in the executable, write the initializer into the space, and be done. There's no provision for calling malloc as you've done above during initialization--you'll need to do that inside of main (or something you call from main).

#include <stdlib.h>

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

int main() { 
    init();
    // ...
}

In this case, the code you have in main never actually uses head though, so you may be able to skip all of the above without a problem.

查看更多
相关推荐>>
3楼-- · 2020-02-07 02:39

head is a global varibale. Global and static varibales must be initialized by constant expressions, i.e. literals. so you can't do

node* head = (node *)malloc(sizeof(node));
查看更多
家丑人穷心不美
4楼-- · 2020-02-07 02:42
 9  node* head = (node *)malloc(sizeof(node));
 10 
 11 if(head == NULL){
 12     printf("\n malloc for head node failed! \n");
 13 }

These lines are not possible outside the main() because any function call or executable should be inside the main() function or any function called from main.

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

Only function definitions or any global initialization is possible outside main() but initializer must be constant expression`.

You can declare the head as global but initialization is wrong.

Do it like this :

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


void function () // any function 
{
 head = malloc(sizeof(node));
}

For linked.c:11:1: error: expected identifier,

if statement cannot be outside any function. In your case , put these lines inside main and problem solved

查看更多
Anthone
5楼-- · 2020-02-07 02:43

You can't use malloc() in global scope. or you can do like follow

#include<stdio.h>
#include<malloc.h>
  :
node* head
  :
  :
int main(){
  :
  :
head = (node *)malloc(sizeof(node));
  :
  :
}
查看更多
登录 后发表回答