Reputation: 1181
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?
Upvotes: 1
Views: 233
Reputation: 183878
You misunderstand,
unsigned long * foo = (unsigned long *) 0x200000;
interprets 0x200000 as the address of an unsigned long
. Since it is extremely unlikely that that is the address of an unsigned long
that you can legitimately access in your programme,
std::cout<<foo[0];
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.
Upvotes: 5
Reputation: 15284
type * pointerName = addressItPointsTo;
pointerName[0]
is same as *pointerName
, means dereference the pointer and get the value at the address it points too. It just happens to be 0, however it usually cause a segmentation fault.
Upvotes: 0