Code:
int main(){
short a=1; // #1
char *p=(char*)&a;
*(p)=1; // #2
cout << a << endl; // Output: 1
*(p+1)=2; // #3
cout << a << endl; // Output: 513
}
From my understanding, the output should be as shown in the picture below, 257 and then 258.
Is there any reason I got different result when I run the program above ?

Update:
I know this is Undefined behavior, but still, does this mean that the decimal to binary conversion is not done as usual: right to left, but instead is done left to right for example:
binary(a)=1000 0000 | 0000 0000
so *(p)=1; will make binary(a)=1000 0000 | 0000 0000 which is 1 in decimal
and *(p+1)=2; will make binary(a)=1000 0000 | 0100 0000 which is 513
which exactly the output of the program.
What happens here is due to the fact that we have a 2-byte
shortin a little endian CPU architecture. The standard does not require that the architecture be LE, so in any case this program can generate a number of different results when run on different systems.A
shorthere is laid out in memory with the least significant byte (LSB) first:ppoints at the LSB and sets is to1:The result when interpreted as a
shortis LSB + 256 * MSB, i.e. 1 + 0 * 256 = 1pthen points at the MSB (which is on the next memory address) and sets is to2:Result when interpreted as a
short: 1 + 2 * 256 = 513