c++ - Dereferencing addresses of one type as addresses of another -
this question applies coding language allows users manipulate pointers, asking in regards c++.
suppose have 2 types of same size, example, suppose (long) , (int) both 8 bytes in size. let's declare (long) , (int):
long somelong = 10; int someint = 20;
suppose address of somelong
, someint
x , y, respectively, , suppose in hexadecimal, y = x + 80. if try manually move x y , dereference it, not value of 20 expect. why this?
cout << &somelong + 10 cout << &someint // these 2 return same starting address location cout << *(&somelong + 10) // dereferences int long, not return 20!
i believe it's technically implementation dependent, there's no guarantee.
on other hand, in experience using differently typed pointers same memory in practice tends work way expect to.
and this:
#include <iostream> using namespace std; int main() { long somelong = 10; int someint = 20; cout << &somelong + 1 << '\n'; cout << &someint << '\n'; cout << *(&somelong + 1); return 0; }
works me such outputs 20.
to hope answer why doesn't you, have see actual code. , know compiler you're using.
Comments
Post a Comment