分配内存时出错“初始化元素不是常量”

时间:2012-11-29 07:17:04

标签: 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 } 

编译错误:

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

我正在尝试一个简单的链接列表程序。它没有完全完成。我收到了编译错误。无法理解为什么会这样。

4 个答案:

答案 0 :(得分:7)

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

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

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

只能在main()之外进行函数定义或任何全局初始化,但初始化程序必须为constant expression`。

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

这样做:

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


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

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

if语句不能在任何函数之外。 在您的情况下,将这些行放在main中并解决问题

答案 1 :(得分:7)

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

#include <stdlib.h>

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

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

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

答案 2 :(得分:3)

head是一个全局变量。全局变量和静态变量必须通过常量表达式(即文字)初始化。所以你不能这样做

node* head = (node *)malloc(sizeof(node));

答案 3 :(得分:0)

您不能在全局范围内使用malloc()。    要么 你可以这样做,按照

#include<stdio.h>
#include<malloc.h>
  :
node* head
  :
  :
int main(){
  :
  :
head = (node *)malloc(sizeof(node));
  :
  :
}