Why does the given code give the following output.
#include <stdio.h>
int main(void)
{
int x = 0x12345678;
unsigned short *p = &x;
unsigned char *q = &x;
printf("%x %x\n",*p++,*p++);
printf("%x %x %x %x\n",q[0],q[1],q[2],q[3]);
return 0;
}
Output:
1234 5678
78 56 34 12
and not:
1234 5678
12 34 56 78
The thing which I feel could be the answer is the endianness of the architecture must be causing it. But I can not comprehend how, because the whole 4-byte
must be stored in a contiguous manner.
Also don't *q++
and *(q+1)
point to the same address?
q++
has the value ofq
but is incremented after it's value has been returned.q + 1
has the value ofq + 1
, which is different fromq
.