简体   繁体   中英

Why use **head (and not *head) in RemoveHead(node) function?

In most of the explanations in the book the author insists of using **list passing instead of *list, however as per my understanding I feel there is nothing wrong in *list. Please someone explain me in detail if i am wrong. For example, to delete head of a linked list, the author says the below code is wrong.

void RemoveHead(node *head)
{
   node *temp = head-> next; /* line 1 */
   free(head);
   head = temp;
}

Instead he says the below code must be used

void RemoveHead(node **head)
{
   node *temp = (*head)-> next;
   free(*head);
   *head = temp;
}

In your first example:

head = temp;

Does nothing outside the function, it only sets the local variable head to temp inside the function. Whatever variable the caller passed in will remain unchanged. The author is correct, you need to use pointers or (better) references (if you're using C++).

When passing a node* as the argument, you can free, and modify the contents of the memory address pointed by that pointer. However, modifications performed on the pointer itself will not be seen from outside the function, since the pointer is passed by value.

On you second example, since you are passing a pointer to the head pointer, you can actually modify the actual head pointer, not just the memory pointed by it.

So in your second function, when *head = temp; is executed, you are modifying the address to which the pointer passed as argument points to.

Therefore, the author is right.

Author is right. ** is effectively pass by reference (ie you can change 'head').

In your version (pass by value), head remains unchanged in the calling code.

Well. When you want to modify a integer variable inside a function, you pass it by reference. That is, you pass its address.

int x = 5;

void modify_value (int* x)
{
    (*x) = 7; // is not 5 anymore
}

With pointers is the same. If you want to modify a pointer. You have to pass it by reference. That is, you have to pass its address. Which is a pointer to a pointer.

int* ptr_x = &x;

void modify_pointer (int** ptr_x)
{
    *ptr_x = NULL; // is not &x anymore
}

The author is correct. In your first example, you're modifying a local copy of head - the caller won't notice that anything has changed. head will still have been freed, so you're on track for a crash in pretty short order. You need to pass a pointer to modify the caller's variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM