Generally a short
variable must be at 2-byte align address, but is there any problem if I try to point it at an odd address?
I try this code on VC++ 2008 and it runs properly so can you explain why?
unsigned char ca[10];
unsigned short *s1 = 0;
memset(ca, 1, 10);
s1 = (unsigned short*)&ca[0];
printf("s1 = %d\n", *s1);
s1 = (unsigned short*)&ca[1];
printf("s1 = %d\n", *s1);
In the code snippet above, ca[0]
or ca[1]
there is one certainly at the odd address, so it is not 2-byte alignment, but s1
is perfectly assign to both ca[0]
and ca[1]
.
So is this code correct as expected and is it recommended to do it this way? I would like to have a portable method that read any two bytes in an byte array as a short variable to work well in almost all platforms/compilers.
Thank you very much.