问题
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?
回答1:
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;
}
回答2:
If you use a double pointer, you can pass in the address of the head so your functions can modify the actual pointer. This way you don't need to return the new head.
回答3:
Because if you are using dlistint_t *head
variable instead of using dlistint_t **head
variable in function parameter then, changes made in variable head
in function dlistint_t *add_dnodeint(dlistint_t **head, const int n);
will be local to this method. Since you are using Node*
so changes done in variable head
is local to that function. If you want to reflect these changes even after function call(which you obviously wants to) then use dlistint_t **head
.
来源:https://stackoverflow.com/questions/44786246/linked-lists-single-or-double-pointer-to-the-head