I am messing around a little with pointers. Please take a look at the following results (addresses).
1st code:
#include <iostream>
int main(){
int a = 5;
void* pointer = &a;
std::cout << a << std::endl << &a << std::endl;
std::cout << pointer << std::endl ;
std::cin.get();
}
Result:
2nd code:
#include <iostream>
int main(){
int a = 5;
void* pointer = &a;
std::cout << a << std::endl << &a << std::endl;
std::cout << &pointer << std::endl ;
std::cin.get();
}
Result:
Why does the address of the variable a
change between the two codes?
CodePudding user response:
In the first case, you never take the address of pointer
, so pointer
can be stored in a register, or even not at all. (Modern compilers are very clever, and modern machines have many registers.)
For instance, gcc 11 keeps the value in a register without optimization, and with -O2
it just inserts the address of a
directly. (Assembly here, for the curious.)
In the second case, you do take the address of pointer
, so it must be stored somewhere in memory.
This means that a
might be stored in a different place in order to make room for it.
Also, some platforms randomize storage locations in order to make programs less hackable, so it's usually not a good idea to assume that things will have the same address in different "runs".
CodePudding user response:
In the first code poiner
stores the address of variable a
, and by command.
std::cout<<pointer<<std::endl;
You print the address of a
. That's it.
In the second code pointer
also stores the address of variable a
, but &pointer
is the address of variable pointer
. Try the following
#include <iostream>
int main(){
int a = 5;
void* pointer = &a;
void** pointer_to_pointer = &pointer;
std::cout << a << std::endl << &a << std::endl << pointer << std::endl;
std::cout << &pointer << std::endl << pointer_to_pointer;
std::cin.get();
}
The output for me is
5
0x7aba1bd92e94
0x7aba1bd92e94
0x7aba1bd92e98
0x7aba1bd92e98
CodePudding user response:
It is very simple.
int a
and void* pointer
are two distinct variables or I better say memory locations on the stack. a
holds a value like 5 in its location. pointer
holds the address to a
's memory location. pointer
itself is stored in a different location and when you write std::cout << &pointer << std::endl;
it will print the address of the pointer
variable, not the contents of it which is a
's address.
As a simplified example:
Consider 0x4 as the address of pointer
itself and the value inside it is 0xC. This value points to a
's location. In order to read the value of a
(which is 5), you first have to go to 0x4 to read its content. Its content is 0xC and now you have successfully found out that a
's location is 0xC. Then you have to go to 0xC and at that address, you will find the value 5.
You look at -> 0x4( content == 0xC ) -> 0xC( content == 5 ) -> done!