Search code examples
cpointerspass-by-referencepass-by-valuefunction-declaration

I'm having a problem understanding double pointers


I'm making a program to add items to a LIFO (last in first out) array, where the elements are inserted at the start of the array.

Here is my code:

typedef struct neud{
    int num;
    struct neud *next;
}neud;

void add(neud** head,int val){
    //creat a new neod
    neud* newNeod;
    newNeod = malloc(sizeof(neud));
    //assigning
    newNeod->num = val;
    newNeod->next= *head;
    //change the head;
    *head = newNeod;
}

int main()
{
     neud* head = NULL;
     add(&head,10);
     add(&head,20);
     add(&head,30);
     return 0;
}

Everything works fine, but I don't understand precisely the need for a double-pointer here. Can someone explain this?


Solution

  • Consider this simple program.

    #include <stdio.h>
    
    void f( int x )
    {
        x = 10;
    }
    
    int main( void )
    {
        int x = 0;
    
        f( x );
    
        printf( "x = %d\n", x );
    }
    

    The program output is

    x = 0
    

    That is the function f deals with a copy of the value of the variable x passed to the function. So changing the copy within the function has no effect relative to the original variable x.

    To change the original variable x in the function you need to pass it by reference. In C passing by reference means passing an object indirectly through a pointer to it. Thus dereferencing the pointer within the function you get a direct access to the object pointed to by the pointer and can change it.

    Compare the program below with this program above

    #include <stdio.h>
    
    void f( int *px )
    {
        *px = 10;
    }
    
    int main( void )
    {
        int x = 0;
    
        f( &x );
    
        printf( "x = %d\n", x );
    }
    

    The program output is

    x = 10
    

    So if you will declare your function like

    void add(neud * head,int val);
    

    and call it like

    add( head, 10 );
    

    then the function will deal with a copy of the value of the original pointer head. The value of the pointer itself will stay unchanged. So you need to pass the pointer by reference that is the function should be declared like

    void add(neud** head,int val);
    

    and called like

    add( &head, 10 );