Search code examples
cpointersdereferencedouble-pointer

How double pointer really behaves this way?


Is not that true that double pointer store address of a pointer only? How it can then store an integer address?

{
    int **ptr,a;
    a = 10;
    ptr = &a; 

    printf("value of a = %d\n",*ptr);  //why it works?
    printf("value of a = %d\n",**ptr); //why it doesnt work?

}

Solution

  • As for your problem, because you make ptr point to &a, then doing *ptr will lead to the same result as doing *(&a) which gives you the value of where &a is pointing, which is the value of a. It's semantically incorrect though, and could lead to other problems if the size of int * (which is what *ptr really is) is different from the size of int (which is what a is).

    When you do **ptr you treat the value of a as a pointer, and dereference it. Since 10 is unlikely to be a valid pointer on a modern PC you will get undefined behavior.


    You say "double pointer store address of a pointer", and that's correct. A pointer to a pointer can store an address (pointer) of a pointer. But &a is not an address of a pointer, it's the address of the non-pointer variable a.

    For a "double pointer" (pointer to pointer really) to work, you need something like

    int a = 10;
    int *ptr = &a;  // Make ptr point to the variable a
    int **ptrptr = &ptr;  // Make ptrptr point to the variable ptr
    

    After this, *ptrptr == ptr, and **ptrptr == *ptr and **ptrptr == a.

    Somewhat graphically the above could be seen something like

    +--------+     +-----+     +---+
    | ptrptr | --> | ptr | --> | a |
    +--------+     +-----+     +---+