【发布时间】:2015-11-23 19:58:48
【问题描述】:
我有一个关于通过函数传递 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);
}
如您所见,当我尝试打印 rec->data 时发生错误。为什么会发生错误?我想既然指针rec和head都指向堆中的同一个节点,应该不会有什么问题吧?
谢谢。
【问题讨论】:
-
你需要通过
struct node**来插入,比如insert(&head...。否则 head 不会改变,因为函数只接收其值的副本。 -
你可以通过重新定义
insert函数的参数来通过指针指向列表的头部 -
另外,您可能需要
temp->next = *rec(假设您传递了一个双指针),否则您将丢失列表的其余部分。 -
C 中没有引用。
标签: c pointers linked-list pass-by-reference