Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

It makes *iPtr2 point to whatever iPtr1 points to. And as iPtr2 points to iPtr1 it's the same as iPtr1 = iPtr1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top