C语言链表头插法代码编译报C4047指针类型不匹配警告原因求解
问题原因分析
- 核心触发原因:函数名大小写不匹配 + 缺少函数前置声明
C语言严格区分大小写,你定义的函数名为InsertAtBeginning(Beginning首字母B大写),但main函数中调用时写的是InsertAtbeginning(beginning首字母b小写),二者会被编译器识别为两个完全不同的函数。
同时C语言要求函数调用前必须有声明或定义,否则编译器会默认给未声明的函数赋予int类型的返回值。你调用的小写拼写的函数不存在且没有提前声明,编译器默认它返回int值,把int值赋值给struct node*类型的head变量,就触发了类型间接层级不一致的C4047警告。 - 代码还存在其他隐藏问题:
- 缺少
<stdlib.h>头文件:malloc函数定义在该头文件中,不引入的话也会触发隐式声明警告 - malloc参数错误:你当前写的
sizeof(struct node*)是获取结构体指针的大小,实际应该传入sizeof(struct node)来申请整个结构体的内存空间,否则会出现内存分配不足,后续访问结构体成员会触发未定义行为。
修正后的完整代码
#include<stdio.h> #include<stdlib.h> // 引入malloc对应的头文件 struct node{ char data; struct node* next; }; // 函数前置声明,拼写和定义完全一致 struct node* InsertAtBeginning(struct node* head, char key); int main() { struct node* head = NULL; // 调用时函数名拼写和声明/定义保持一致 head = InsertAtBeginning(head,'g'); head = InsertAtBeginning(head,'f'); return 0; } struct node* InsertAtBeginning(struct node* head, char key) { // malloc参数修改为结构体的大小 struct node* temp = (struct node*) malloc(sizeof(struct node)); temp->data = key; temp->next = head; head = temp; return head; }
内容的提问来源于stack exchange,提问作者Francis
相关产品推荐
相关产品推荐

