将链表头传递给函数作为C中的地址

Lun*_*una 2 c pointers linked-list pass-by-reference

我有一个关于通过函数传递C中链表头部的问题.所以代码是这样的:

#include <stdio.h>
//Defining a structure of the node
struct node { 
    int data;
    struct node* next;
    };

void insert (struct node* rec, int x) {
    struct node* temp = (struct node*)malloc(sizeof(struct node));
    temp->data = x;
    temp->next = NULL;
    rec = temp; // head and rec is now pointing to the same node
}

void print(struct node* rec){
    printf("%d", rec->data); //error occurs here
    puts("");
}

main(){
    struct node *head = NULL; //head is currently pointing to NULL
    insert (head, 5); //Passing the head pointer and integer 5 to insert()
    print(head);
}
Run Code Online (Sandbox Code Playgroud)

如您所见,当我尝试打印rec->数据时发生错误.为什么会出现错误?我以为既然指针rec和head都指向堆中的同一个节点,那应该没有任何问题?

谢谢.

nim*_*odm 5

您可以struct node**按照@ sje397的建议传递一个.

但是,我会建议以下设计(在我看来也更容易推理):

/* returns the new head of the list */
struct node *insert (struct node* current_head, int x) {
    struct node* temp = (struct node*)malloc(sizeof(struct node));
    temp->data = x;
    temp->next = current_head;
    return temp;
}
Run Code Online (Sandbox Code Playgroud)

并使用它

head = insert(head, 5);
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我也会重命名函数push_front.

为了完整起见,我认为@ sje397意味着类似下面的内容(每个C程序员一次又一次地重写典型的链表代码......):

void insert(struct node **head, int x) {
    struct node* new_head = (struct node*)malloc(sizeof(struct node));
    new_head->data = x;
    new_head->next = *head;

    *head = new_head;
}
Run Code Online (Sandbox Code Playgroud)