I am trying the following code:
unsigned long * foo = (unsigned long *) 0x200000;
So, as I understand it, foo points to the unsigned long 0x200000. Now, if I try,
std::cout<<foo[0];
I thought this should print the value 0x200000 (may be in decimal). Because, foo[0] = *(foo + 0) = 0x200000.
But, it actually prints 0.
What I am missing here?
You misunderstand,
interprets 0x200000 as the address of an
unsigned long. Since it is extremely unlikely that that is the address of anunsigned longthat you can legitimately access in your programme,is almost certainly undefined behaviour, and likely causes a segfault. In your case, though, accessing that memory location didn’t cause a segfault and the bits there were interpreted and printed as an
unsigned long, they happened to be all 0.