初始元素不是常数 [英] initializer element is not constant

查看:136
本文介绍了初始元素不是常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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 } 

编译错误:

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

我想一个simplelinked列表铂族金属。它不是全面完成。我得到一个编译错误。不明白为什么这个haappened。

I'm trying a simplelinked list pgm. Its not fully completed. I'm getting a compilation error. COuldn't understand why this haappened.

推荐答案

正弦你定义作为一个全球性的,它的初始化需要一个恒定的 - 基本上下,编译器/链接器应该能够在可执行为其分配空间,写初始化成的空间中,并进​​行。有没有规定调用的malloc 如你在初始化时做以上 - 你需要做的

Sine 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();
    // ...
}

在这种情况下,code你在从来没有真正使用虽然,所以你可以是能够跳过上述所有的没有问题。

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.

这篇关于初始元素不是常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆