Reputation: 13
# include <stdio.h>
int main()
{
char p[]={0x01,0x02,0x03,0x04};
int *q = p;
printf("%x",*q);
return 0;
}
When I run the above code, the answer is 4030201. Why?
Upvotes: 0
Views: 376
Reputation: 5407
It is because you compile and run your code on little-endian architecture machine (x86 for example)
At first you put 4 bytes in memory in order: 01 02 03 04
. Than convert pointer to this array to pointer to int. On little-endian machine memory block 01 02 03 04
represents integer value 0x04030201 which is printed on next step.
See https://en.m.wikipedia.org/wiki/Endianness for more information
Upvotes: 1