I am confused about pointer pointing to address of variable
it points to last two bytes how does this work
#include <iostream>
using namespace std;
int main()
{
int i = 1;
short *j = (short*)&i;
cout << *j << endl;
}
.
A pointer normally holds the address of the beginning of the referred-to item.
From the sound of things, you're apparently using a little-endian system [edit: which is no surprise -- just for example, current (Intel) Macs and all Windows machines are little-endian], which means the least significant byte of your 4-byte int comes first in memory instead of last:
0000001 00000000 00000000 00000000
When you use a pointer to short to look at the first two bytes, you get:
0000001 00000000
which is exactly how it expects to see a value of 1 represented as a two-byte number, so that's what you get.
As implied by the name "little-endian" there are also big-endian systems, where the data would be laid-out as you've illustrated above. On such a machine, you'd probably get the results you expected. Just to be complete, there are also a few systems that use rather strange arrangements that might run something like byte1 byte0 byte3 byte2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With