You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用函数引用传递修改单链表表头的指针类型警告修复咨询

修复单链表头部添加元素的指针类型不匹配警告

问题根源

你在main函数里对指针h的类型定义完全错了:

  • head是struct node*类型的指针,它的地址&head属于struct node**类型(指向指针的指针)
  • 但你把h定义成了struct node*,强行赋值h = &head必然触发类型不匹配警告,后续把h传给要求struct node**的addatbegin函数,自然也会报同样的错。

修复方案

有两种简单的修复方式,选哪种都能解决警告:

方案1:修正h的类型

把h的定义改成struct node**,匹配&head的类型:

int main(){
    struct node *head;
    struct node **h; // 改为指向指针的指针
    h = &head;
    head = (struct node*)malloc(sizeof(struct node));
    head->val=2;
    head->next= (struct node*)malloc(sizeof(struct node));
    head->next->val = 3;
    printlist(head);
    addatbegin(h,4);
    printlist(head);
}

方案2:直接传&head(更简洁)

完全没必要额外定义h变量,调用addatbegin时直接传入head的地址就行:

int main(){
    struct node *head;
    head = (struct node*)malloc(sizeof(struct node));
    head->val=2;
    head->next= (struct node*)malloc(sizeof(struct node));
    head->next->val = 3;
    printlist(head);
    addatbegin(&head,4); // 直接传head的地址
    printlist(head);
}

额外优化提示

  • 在C语言里,malloc的返回值不需要强制转成struct node*,因为void*可以隐式转换为其他指针类型,强制转换反而可能掩盖一些低级错误(比如忘了包含stdlib.h时的编译报错)。
  • 记得在程序结束前遍历链表释放所有节点的内存,避免内存泄漏。

内容的提问来源于stack exchange,提问作者Cap_Void

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 00:52:20