通过函数将链接列表头作为C中的地址传递 [英] Passing a linked list head through a function as address in 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屋!