linked list and pointers

Hello everybody. I did not understand why double pointer is used(pointer to pointer) in function arg and *head_ref used and &head in function call parameters. please explain. WHAT IF I WANT TO USE ONLY head IN THE FUNCTION ? example head_ref = new_node and NOT *head_ref = new_node
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void push(Node** head_ref, char new_data)  
{  
    Node* new_node = new Node(); 
    new_node->data = new_data;  
  /* link the old list off the new node */
    new_node->next = (*head_ref);  
  /* move the head to pochar to the new node */
    (*head_ref) = new_node;  
}  
  
/* Driver code*/
int main()  
{  
    // Let us create linked list 1->2->3->4  
    Node* head = NULL;  
    push(&head, 4);  
    push(&head, 3);  
    push(&head, 2);  
    push(&head, 1);
In the function main, when push has been called many times, the pointer head needs to point to the start o fthe linked list.

If we passed just a pointer to the function, then the function would receive a copy of head (pass-by-value) and would change that copy, and in main the original head would still be NULL.

Instead, passing a pointer to head allows the function to change head.


I would be remiss if I did not say that this is awful C++ code. It's basically C, with new being used. Written in idiomatic C++, this would be much easier to follow.
thank you so much sir
you can do it with a reference and that makes it easier to understand the intent, but its odd looking.

void foo(int *& p)
{
p = new int; //this changes the p that was passed in. if you take the & off, it does not (and leaks memory to boot).
}

using ** works but makes the intentions less clear, and that is because pointers and references are extremely similar things, with just enough differences to occasionally throw you for a loop if you forget them. The reference also gets rid of the extra layer of pointer code.
Last edited on
thank you so much
Topic archived. No new replies allowed.