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;
}
.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.