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)
Singly-linked list consists of nodes connected to each other using the next link. The initial node in the chain is commonly referred to as the "head of the list".
Whenever you are creating a linked list, we have to initialize it and since it doesn't have any nodes in the start (empty linked list in the beginning), the start/head points to null. That's what is meant by *head=NULL.
there is no difference at all between the two declarations. The point you make about node* next not pointing anywhere applies to node *next too. In both the cases, you need extra code to make the given next point to actual data.
A node is a structured variable (or object) containing at least one field whose type is a pointer type.
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.
struct node **head
you are passing the address of the pointer of head
there by making it possible to make it refer/point to a different memory area. With struct node *head
you can't modify head
to point anywhere else
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With