Search code examples
cpointersmemory-managementlinked-listpointer-to-pointer

PointerToPointer : How to return the modified values/structure back to the original list?


While writing the add function for Linked List I came up with the following piece of code

    int addNode(node ** head)
        {
1.      node * ptr = *head;
        if(ptr==NULL)
        {
            ptr = (node *)malloc(sizeof(node));
            ptr->next = NULL;
            ptr->val = (char *)malloc(10);
            strcpy(ptr->val,"1");
2.          *head = ptr;
        }//Rest omitted

Now as far as my understanding of pointer to pointer goes, when i call this function

addNode(&n)

(n is defined as node * n) I send the address of the pointer n. head = &n as of now? At 1 I make ptr point to n i.e. ptr = &n? Is that right? What I don't understand is why do I need to set *head = ptr? Isn't ptr already directly making changes to n? And don't both ptr and *head point to n?

Thanks!


Solution

  • ptr is the working copy of *head. with

    node *ptr = *head;
    

    you make a copy. If you use ptr, no changes to head are done, because you have copied the pointer but not the ptrptr. head is the same as n, it's just the name of n in your function. So ptr does not change n - you use the line

    *head = ptr;
    

    to change n.