使用函数引用调用来更改单链表的头时出错

问题描述 投票:0回答:1

我正在学习 C 中的链表,并且在尝试使用函数在链表开头添加值时遇到错误

#include<stdio.h>
#include<stdlib.h>
struct node{
    int val;
    struct node *next;
};
void printlist(struct node *head){
    struct node *current = head;
    while(current!=NULL){
        printf("%d\n",current->val);
        current = current->next;
    }
    printf("------------------------\n");
}
void addatbegin(struct node **head,int x){
    struct node *new;
    new = (struct node*)malloc(sizeof(struct node));
    new->val = x;
    new->next = *head;
    *head = new;
}
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);
}

在函数 addatbegin(struct node **head,int x) 中,我给出了一个双指针来尝试使用引用传递来更改链表的头。代码运行并工作,但是我收到这些错误/警告.

main.c: In function ‘main’:
main.c:33:7: warning: assignment to ‘struct node *’ from incompatible pointer type ‘struct node **’ [-Wincompatible-pointer-types]
   33 |     h = &head;
      |       ^
main.c:40:16: warning: passing argument 1 of ‘addatbegin’ from incompatible pointer type [-Wincompatible-pointer-types]
   40 |     addatbegin(h,4);
      |                ^
      |                |
      |                struct node *
main.c:23:31: note: expected ‘struct node **’ but argument is of type ‘struct node *’
   23 | void addatbegin(struct node **head,int x){
      |                 ~~~~~~~~~~~~~~^~~~
2
3
------------------------
4
2
3
------------------------

我该如何解决这个问题?

c function pass-by-reference singly-linked-list
1个回答
0
投票

编译器正在告诉您需要了解的内容。您传递的是

struct node *
而不是
struct node **
。您需要使用
&
来传递
head
指针的地址。

int main(void) {
    struct node *head = malloc(sizeof(struct node));
    head->val = 2;
    head->next = malloc(sizeof(struct node));
    head->next->val = 3;
    printlist(head);
    addatbegin(&head, 4);
    printlist(head);
}
© www.soinside.com 2019 - 2024. All rights reserved.