This question already has answers here:
Closed 5 years ago.
Why isn't sizeof for a struct equal to the sum of sizeof of each member?
(11个答案)
我正在尝试将字节数组复制到结构:
实际字节数:
00000000 | ff 53 4d 42 72 00 00 00 00 08 01 c8 00 00 00 00 | .SMBr...........

目标结构:
typedef struct {
    uint8_t protocol[4];
    uint8_t command;
    uint32_t status;
    uint8_t flags;
    uint16_t flags2;
    uint16_t pidHigh;
    uint16_t somethingElse;
} MyStruct;

但出于某种原因,myStruct.status中的字节不是它们应该是的:
printf("%x", bytes[4]);
  => 72          // Ok

printf("%x", myStruct.command);
  => 72          // Ok

printf("%02x%02x%02x%02x", bytes[5], bytes[6], bytes[7], bytes[8]);
  => 00000000    // Ok

printf("%"PRIX32, myStruct.status);
  => C8010800    // What?! Why did it take the next 4 bytes... and reversed them?

用于复制这些字节的代码:
MyStruct myStruct;
memcpy(&myStruct, bytes, 16);

这段代码运行在ARM(iPhone 5)上,这可能解释了输出的小端性,但它并不能解释为什么被复制的字节中有一个+4字节的偏移量。
这里发生了什么事?

最佳答案

编译器将结构中的元素对齐,以便它们在内存中占用的空间等于4的倍数。
因此,基本上,command应该只使用1个字节,在status之前后面跟着3个字节的垃圾。
通过设置以下内容,可以告诉编译器不要这样做:

#pragma pack(1)

09-10 04:49
查看更多