简体   繁体   中英

C - deconstructing a struct into char array

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).

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:

  • Size of struct ztest may include padding
  • char may be signed or unsigned
  • Bytes of uint16_t may be stored in big-endian or little-endian form

It 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM