I have this piece of code that I saw it somewhere and I tried to figure out how it works, but I couldn't.
This is it :
#include <iostream>
using namespace std;
int main() {
int a = 2;
char * p = (char *) &a;
*(p + 1) = 1;
cout << (int *) p << endl;
return 0;
}
I thought that in p it stores the binary of variable a like 00000010
. Than in the next immediate address it stores 00000001
. When I try to print (int *)
p it takes 4 bytes from that address and converts it into int.
When I ran the program the result wasn't that expected. It shows only the address of variable a
. No change observed.
Could you please explain me how this works and why ?
PS : If I want to show the value of p it shows only 2 not 258 how I expected.
cout << (int *) p << endl;
would be the same as cout << &a << endl;
(just the address of a
).
int a = 2;
cout << sizeof(a) << endl; // 4 (int is 4 bytes)
cout << sizeof(&a) << endl; // 8 (64b machine, so pointer is 8 bytes)
char *p = (char *) &a; // p points to first byte of a (normally 4 bytes)
cout << (int) *p << endl; // 2 // Little Endian, the first byte is actually the last
cout << (int) *(p + 1) << endl; // 0
*(p + 1) = 1; // second byte of a is now set to 1
cout << a << endl; // a now changes to 258 (0000 0001 0000 0010)
PS : If I want to show the value of p it shows only 2 not 258 how I expected.
The value of p
is the address of the object to which it points. It seems your confusion is here. If you dereference p
you will get value of object to which it points, that is different.
Hence, in your case p
is initialized to address of a
. Afterwards, nothing is assigned to it (eg nowhere you do p=&SomeOtherObject
).
cout << (int *) p << endl; // Print value of pointer -which is address
So above you are printing value of p
which is address of a
.
As noted keep in mind
*(p+1) = 1
might be undefined behaviour if sizeof (int)
is same as sizeof (char)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.