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);
}
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?
Thank you.
Redefine the
insert
function to:In C there is no pass by reference.
Your insert function isn't inserting a node in the list, its just changing the node which the head points to. Because of
temp->next = NULL
the list will always contain two nodes.Another error is that you're just modifying a local copy of the head node. To fix this You have 3 choices:
-You can make the head node global
-You can pass a pointer to the head node(pointer to pointer) to the function.
-You can return the modified head node by the function.
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):
and use it like
In this case I would also rename the function something like
push_front
.Just for completeness, I think @sje397 meant something like the following (Typical linked list code rewritten again and again by every C programmer...):