C - 将结构解构为char数组

时间:2021-06-21 19:58:27

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

这是在openwrt系统ar71xx上运行的。目的是通过串行线发送char数组(如果相关的话)。

2 个解决方案

#1


3  

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
  • struct ztest的大小可能包括填充

  • char may be signed or unsigned
  • char可以是签名或未签名

  • Bytes of uint16_t may be stored in big-endian or little-endian form
  • uint16_t的字节可以以big-endian或little-endian形式存储

It appears that your system adds one byte of padding to struct ztest, uses signed chars, and stores uint16_t with the most significant byte at a lower address.

您的系统似乎在struct ztest中添加了一个填充字节,使用了有符号的字符,并将uint16_t与最高有效字节存储在较低的地址。

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.

0x17的值是填充字节的“垃圾”。 0x88的值进行符号扩展以作为signed int打印,从而导致0xFFFFFF88打印输出。

#2


0  

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.

结构ztest的大小为4.它有一个无符号字符,一个填充字节和两个短字节。所以当试图显示dd [1]时,你实际上有一个未定义的行为。

#1


3  

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
  • struct ztest的大小可能包括填充

  • char may be signed or unsigned
  • char可以是签名或未签名

  • Bytes of uint16_t may be stored in big-endian or little-endian form
  • uint16_t的字节可以以big-endian或little-endian形式存储

It appears that your system adds one byte of padding to struct ztest, uses signed chars, and stores uint16_t with the most significant byte at a lower address.

您的系统似乎在struct ztest中添加了一个填充字节,使用了有符号的字符,并将uint16_t与最高有效字节存储在较低的地址。

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.

0x17的值是填充字节的“垃圾”。 0x88的值进行符号扩展以作为signed int打印,从而导致0xFFFFFF88打印输出。

#2


0  

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.

结构ztest的大小为4.它有一个无符号字符,一个填充字节和两个短字节。所以当试图显示dd [1]时,你实际上有一个未定义的行为。