If I have:
int j = 8;
int *pointer = &j;
then if I do:
&*pointer == *&pointer
that returns 1
(true
).
But I have a doubt on the second expression:
&*pointer
returns the address pointed by pointer (first evaluated *
then &)*&pointer
returns pointer address and then what it points... but this is the variable not the address. So here is my doubt...&*pointer
dereferences the pointer (1. in the diagram below) to give you the int
object (2.), then takes the address of that object, which of course is the same value as the pointer (1.).
┌─────────┐ ┌───┐
│ pointer ┿━>│ j │
└─────────┘ └───┘
(1.) (2.)
*&pointer
takes the address of the pointer (4.) to get a pointer to that pointer (3.), then dereferences that address to get the pointer again (4.).
┌──────────┐ ┌─────────┐ ┌───┐
│ &pointer ┿━>│ pointer ┿━>│ j │
└──────────┘ └─────────┘ └───┘
(3.) (4.)
The important part that you're missing is that pointer
is the address of the int
and so &pointer
is the address of the address. Dereferencing you that just gives you the pointer again.
pointer
"points" to some address in memory; and it resides at some other address in memory.
&*pointer // (*pointer) - dereference `pointer`, now you have `j`
// &(*pointer) - the address of `j`(that's the data that `pointer` has)
Where as:
*&pointer //(&pointer) - the address of pointer(where pointer resides in memory)
// *(&pointer) - deference that address and you get `pointer`
I always find pointers easier to trace with a picture, so maybe this illustration will help to understand why they are the same:
//In case of &*pointer, we start with the pointer, the dereference it giving us j
//Then taking the address of that brings us back to pointer:
+--&(*pointer)-----------+
| |
memory address 0x7FFF3210 | 0x7FFF0123 |
+------------+ | +-----+ |
data present | pointer = | <---+ +-> | j=8 |----+
| 0x7FFF0123 | ->(*pointer)-+ +-----+
+------------+
//in the *&pointer case, we start with the pointer, take the address of it, then
//dereference that address bring it back to pointer
memory address +------------> 0x7FFF3210 ----*(&pointer)--+
| |
| +------------+ |
data present | | pointer = | <----------- -+
+--&pointer ---| 0x7FFF0123 |
+------------+
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With