Reputation: 3970
Why does the code below produces
09 17 13 FFFFFF88
Where I expect to see
09 13 88
Code below
struct ztest
{
uint8_t a;
uint16_t b;
};
struct ztest zt;
char * dd = (char *) &zt;
zt.a = 9;
zt.b = 5000;
for (i = 0; i < sizeof(zt); i++) {
printf("%02X ",dd[i]);
}
This is running on openwrt system ar71xx. The aim is to send the char array over a serial line (in case that's relevant).
Upvotes: 1
Views: 230
Reputation: 726489
Your code relies on implementation-defined behavior, so it is not possible to predict what you are going to see without knowing the specifics of the system on which it runs:
struct ztest
may include paddingchar
may be signed or unsigneduint16_t
may be stored in big-endian or little-endian formIt appears that your system adds one byte of padding to struct ztest
, uses signed char
s, and stores uint16_t
with the most significant byte at a lower address.
The value of 0x17
is "junk" from the padding byte. The value of 0x88
gets sign-extended for printing as a signed int
, resulting in 0xFFFFFF88
printout.
Upvotes: 3
Reputation: 87
The structure ztest
has size 4. It has one unsigned char, one padding byte, and two bytes for the short. So when trying to display dd[1]
you are actually having an undefined behavior.
Upvotes: 0