Error “initializer element is not constant” when allocate the memory

后端 未结 4 1563
遥遥无期
遥遥无期 2020-12-11 05:13
  1 #include
  2 #include
  3 
  4 typedef struct node_t{
  5     int i;
  6     struct node_t* link;
  7 }node;
  8 
  9 node* head =         


        
4条回答
  •  半阙折子戏
    2020-12-11 05:37

    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 
    
    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.

提交回复
热议问题