We are given a task and a struct of linked list:
typedef struct dlistint_s
{
int n;
struct dlistint_s *prev;
struct dlistint_s *next;
} dlistint_t;
And the function with the following prototype:
dlistint_t *add_dnodeint(dlistint_t **head, const int n);
What are the advantages and why one would be using a double pointer to the head when creating a function?
The reason to pass pointer to pointer to head is that any modification to the pointer head will be seen in the caller function and you do not have to return head from your function.
For example, consider this simple node:
struct Node{
int data;
struct Node *next;
};
A function to add a node to the list at front
struct Node *add_node (struct Node *list, int n){
struct Node *new_node = malloc(sizeof(struct Node));
if(new_node == NULL){
printf("Memory allocation failed\n");
exit(EXIT_FAILURE);
}
new_node->data = n;
new_node->next = list;
return new_node;
}
If we need to assign the new_node to the list instead of returning it then we need to modify the above function and remove the return statement and put a statement
list = new_node;
But, that will not work!
This is because in C, like all arguments, pointers are passed by value.
That means the list contains the copy of the pointer value passed to add_node function and not the pointer passed to this function itself.
That's where we need pointer to pointer.
void add_node (struct Node **list, int n){
struct Node *new_node = malloc(sizeof(struct Node));
if(new_node == NULL){
printf("Memory allocation failed\n");
exit(EXIT_FAILURE);
}
new_node->data = n;
new_node->next = *list;
*list = new_node;
}
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