i saw this question at my c language final exam and the output is 513 and i don't know why
#include <stdio.h>
int main(void){
char a[4] = {1,2,3,4};
print("%d" , *(short*)a);
}
i saw this question at my c language final exam and the output is 513 and i don't know why
#include <stdio.h>
int main(void){
char a[4] = {1,2,3,4};
print("%d" , *(short*)a);
}
Your array of bytes is (in hex):
[ 0x01, 0x02, 0x03, 0x04 ]
If you treat the start of the array not as an array of bytes, but as the start of a short
, then your short has value 0x01 0x02
, and because your processor is "Little Endian", it reads backwards from how humans read it. We would it as 0x0201
, which is the same as 513(Decimal)
If the system this code is being run on meets the following requirements:
Unaligned memory access is permitted (or a
is guaranteed to be short
-aligned)
Little-endian byte order is used
sizeof(short) == 2
CHAR_BIT == 8
Then dereferencing a short *
pointer to the following memory:
| 0x01 | 0x02 | 0x03 | 0x04 |
Will give you 0x0201
, or 513
in base 10.
Also, do note that even if all these requirements are met, aliasing a char []
array as a short *
violates the strict aliasing rule.
The code casts your char*
pointer into short*
one and prints its value.
short in C is represented in 2 bytes, and the binary representation of the first two bytes of your array is 00000001 00000010
but because the processor is a little endian one it reads it as 00000010 00000001
which is 513 in decimal.