Passing a linked list head through a function as address in C
Solution 1
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;
}
and use it like
head = insert(head, 5);
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...):
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;
}
Solution 2
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.
Comments
-
Luna almost 2 years
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.
-
sje397 over 8 yearsThat fixes the mentioned bug, but it's not an insert function.
-
Alex Reynolds over 8 yearsCalling this function gives you nodes that point to
NULL
. So if you think about how a linked list is structured, this doesn't really offer insertion functionality. You need to modifyrec
so that the new node points to it, or vice versa. -
Luna over 8 yearsI see... @sje397 nimrodm Thank you so much for the help! This pointer to pointer thing is getting me confused every time.