通过函数传递链表头作为C中的地址 [英] Passing a linked list head through a function as address in C

查看:23
本文介绍了通过函数传递链表头作为C中的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a question regarding passing the head of a linked list in C through a function. So the code goes something like this:

#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);
}

如您所见,当我尝试打印 rec->data 时出现错误.为什么会出现错误?我想既然指针rec和head都指向堆中的同一个节点,应该不会有什么问题吧?

So as you see, the error occurs when I tried printing rec->data. Why did the error occur? I thought since the pointer rec and head are all pointing to the same node in the heap, there should not be any problem?

谢谢.

推荐答案

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

You could pass a struct node** as suggested by @sje397.

但是,我建议采用以下设计(我认为这也更容易推理):

However, I would suggest the following design (which, in my opinion is easier to reason about too):

/* 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;
}

并像使用它一样

head = insert(head, 5);

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

In this case I would also rename the function something like push_front.

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

Just for completeness, I think @sje397 meant something like the following (Typical linked list code rewritten again and again by every C programmer...):

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;
}

这篇关于通过函数传递链表头作为C中的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆