C语言链表报错:expected expression before 'struct'问题排查求助
C语言链表插入函数的错误分析与修正
先逐个梳理你代码里的问题:
1. 结构体名称拼写错误
你定义的链表结构体是struct Linked_List(带下划线),但在insertAtBeginning函数的参数里写成了struct Linkedlist(无下划线),C语言对标识符的大小写、符号严格区分,这会导致编译器无法识别参数类型。
修正:
void insertAtBeginning(struct Linked_List *LL, char ele[])
2. malloc使用的三个错误
报错行struct Node new_node = malloc(sizeOf(struct Node));存在三个问题:
- 类型不匹配:
malloc返回的是void*类型指针,你却把它赋值给struct Node类型变量,应该定义为指针类型struct Node *new_node - 关键字拼写错误:C语言中获取类型大小的关键字是
sizeof(全小写),不是sizeOf - 可选优化:虽C99及以后标准允许
void*隐式转换为其他指针类型,但显式转换为struct Node*会让代码更清晰
修正后:
struct Node *new_node = (struct Node*)malloc(sizeof(struct Node));
3. 函数调用参数类型不匹配
insertAtBeginning函数要求第一个参数是struct Linked_List*类型指针,但你在main函数里直接传了结构体变量LL,应该传它的地址&LL。
修正:
insertAtBeginning(&LL, string);
4. 额外的初始化问题(避免野指针)
你定义的struct Node head未初始化,它的next和data会是随机值(野指针),建议初始化空链表时让header指向NULL:
struct Linked_List LL; LL.header = NULL; // 空链表头指针设为NULL
另外,插入节点时还需要处理数据拷贝和链表指针链接,完整的insertAtBeginning函数可以补充如下:
void insertAtBeginning(struct Linked_List *LL, char ele[]) { struct Node *new_node = (struct Node*)malloc(sizeof(struct Node)); // 为data分配内存并拷贝字符串 new_node->data = (char*)malloc(strlen(ele) + 1); strcpy(new_node->data, ele); // 链接新节点到链表头部 new_node->next = LL->header; LL->header = new_node; }
程序结束时记得释放链表内存,避免内存泄漏。
内容的提问来源于stack exchange,提问作者Derek Kwon
相关产品推荐
相关产品推荐

