Code
#include <iostream>
using namespace std;
int main()
{
int i = 7;
int *a = &i;
cout << &a << endl; //This Line
cout << *(&a) << endl; //This Line
cout << *(*(&a)) << endl; //This Line
}
Outputs
0x6a12fffdf8
0x6a12fffe00
7
Hi all. I am not very sure what the difference between these three lines is (see code comments). I know the first line prints the address, but I am not sure about the other two.
CodePudding user response:
Lets go line by line:
int i = 7;
i is an int initialized with the integer literal 7.
int *a = &i;
a is a pointer, int*, and is initialized with the address of i. & is the addressof operator here.
cout << &a << endl; //This Line
a itself is also stored at some memory address. The addressof operator applied to a yields that memory address.
cout << *(&a) << endl; //This Line
Here * is the dereference operator. &, addressof, and *, dereference, cancel each other. This line prints the value of a, the address of i.
cout << *(*(&a)) << endl; //This Line
We already know that *(&a) is the value of a, the memory address of i. Applying the dereference operator to the address of i yields the value of i.
In memory it looks like this:
address: &a &i == a
0x6a12fffdf8 0x6a12fffe00
value: a i == *a
0x6a12fffe00 7
CodePudding user response:
You have some data, int i = 7;. This integer is stored in memory (specifically, the stack).
You have a pointer, a, that points to (addresses) this memory int *a = &i; because the int * datatype means an int pointer, and &i means the "address of i".
Your pointer is also stored in memory (again, the stack). You can get its address in much the same way, using &a.
cout << &a << endl; therefore prints the address of the pointer, a.
To dereference (get the value of) a pointer, you use *.
cout << *(&a) << endl; therefore prints the dereferenced value of the address of a, which is the value of a (and therefore the address of i).
Your final line cout << *(*(&a)) << endl; reads as
"Print the dereferenced value of the dereferenced value of the address of a", which is simply i.
CodePudding user response:
Case 1
Here we consider the expression:
&a //this gives us the address of the variable `a`
The above expression gives us the address of variable a.
Case 2
Here we consider the expression:
*(&a) //this gives us the data to which `&a` points which is nothing but the address of variable i
The above expression gives us the data to which &a points. But from case 1 we already know that &a is nothing but the address of variable a. Thus, *(&a) is the same as the address of variable i.
Case 3
Here we consider the expression:
*(*(&a))
The above expression gives us the data to which *(&a) points. Since we already know from case 2 that *(&a) gives us the address of variable i, this implies that *(*(&a)) gives us i itself.
