What is the difference between struct node *head and struct node ** head?
c, linked-list, pointers
Solution
With this function signature:
void changeNode(struct node *head)
You have a pointer to the node, and so you can change that structure. You can't change what the variable head points to. Let's assume the following definition of `struct node`:
struct node
{
int field1;
struct node *next;
}
With the given function signature and `struct node`, consider the following operations can change the structure in the function:
void changeNode(struct node *head)
{
head->field1 = 7;
head->next = malloc(sizeof(struct node));
}
C is pass-by-value: when we pass a variable to a function, the function gets a copy. This is why we pass a pointer to a `struct node`, so that we can change it, and have the effects of those changes outside the function. But we still get only a copy of the pointer itself. So the following operation isn't useful:
void changeNode(struct node *head)
{
// we're only changing the copy here
head = malloc(sizeof(struct node));
}
The changes to `head` won't be reflected outside the function. In order to change what `head` points to, we must use an additional level of indirection:
void changeNode(struct node **head)
{
// now we're changing head
*head = malloc(sizeof(struct node));
// alternately, we could also do this:
*head = NULL;
}
Now the changes to `head` are reflected outside the function.
Problem
I am trying to sort a linked list. I'm confused about when to use `struct node*head` and when to use `struct node **head`, the implementation can be done using both of them. When should I use: ``` void sortedinsert(struct node **head) ``` and when should I use: ``` void sortedinsert(struct node *head) ```