Confused about the result using the reinterpret_cast in C++

55 views Asked by At

For experiment, I create an integer first.

int num = 7;
int* pold = #
std::cout << pold << std::endl;  // 0000005E3DBEF7B0

I am working on 64-bit MSVC and thus assume bit representation of this 'num' should be '00000000 00000000 00000000 00000111'

Now I reinterpret_cast it to a pointer to 'short'.

auto pnew = reinterpret_cast<short*>(pold);
std::cout << pnew << std::endl;  // 0000005E3DBEF7B0

Given that the memory address is same but now it only accounts for 2-bytes, I think the value representing this new short number should be 0 as the first two bytes of '00000000 00000000 00000000 00000111' are '00000000 00000000'.

However, the value pointed by 'pnew' is still 7! I go back to check the value pointed by 'pold' again and the value is 7 as well.

std::cout << *pnew << std::endl; // 7
std::cout << *pold << std::endl; // 7

std::cout << sizeof(*pnew) << std::endl; // 2
std::cout << sizeof(*pold) << std::endl; // 4

I can't figure out the reason why they both represent 7. An 'int' should be '00000000 00000000 00000000 00000111' A 'short' should be '00000000 00000111' But their memory addresses are same, meaning that the first two bytes should be overlapping. How can that be possible?

0

There are 0 answers