Search code examples
cpointersindirection

Dereferencing a double pointer just once?


Hi I have a question about double pointers. For example in this code:

int a, b=2;
int *iPtr1, **iPtr2;

iPtr1  = &a;
iPtr2  = &iPtr1;  
*iPtr1 = b+3;
*iPtr2 = iPtr1;

On the last line *iPtr2 = iPtr1; It that just telling iPtr1 to point back to itself since dereferencing a double pointer just once is like using iPtr1?


Solution

  • Trace the execution with gdb, then you will see that the last line *iPtr2=iPtr1 doesn't change anything. (it's kind of like iPtr1=iPtr1)

    On iPtr2 = &iPtr1;, the iPtr2 already points to the address where iPtr1 THE POINTER lies NOT THE ADDRESS iPtr1 points to.

    Note: you cannot replace iPtr2=&iPtr1 with an *iPtr2=iPtr1, because at that point iPtr2 has garbage value (if it's a local non-static variable) and dereferencing it is undefined behaviour.