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.