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’
我正在尝试一个简单的链表程序。它还没有完全完成。我收到编译错误。无法理解为什么会发生这种情况。
既然你定义了head
作为全局变量,它的初始化器需要是一个常量——基本上,编译器/链接器应该能够在可执行文件中为其分配空间,将初始化器写入该空间,然后完成。没有规定可以打电话malloc
正如您在初始化期间所做的那样 - 您需要在main
(或者你打电话的地方main
).
#include <stdlib.h>
void init() {
head = malloc(sizeof(node));
}
int main() {
init();
// ...
}
在这种情况下,您的代码main
从未真正使用过head
不过,因此您可以毫无问题地跳过上述所有内容。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)