【问题标题】:C/C++ How Nested Structures Are Packed?C/C++ 嵌套结构是如何打包的?
【发布时间】:2020-12-15 19:18:39
【问题描述】:

如果在我的架构上一个单词是 4 个字节,我希望填充以下结构以便至少是一个单词(4 个字节)的大小。

// 4 bytes
struct
{
  uint8_t High : 4;
  uint8_t Low : 4;
} Value;

现在,假设我有以下嵌套结构:

// ? bytes
struct
{
  uint8_t Address;
  struct
  {
    uint8_t High : 4;
    uint8_t Low : 4;
  } Value;
} Register;

这个结构将如何打包? Value 会保持一个字(4 个字节)的大小吗?有两种方法我期望这个结构被打包,但我不知道哪一种是正确的,或者是否是正确的。假设RRegister 的沙子,A 是成员AddressV 是成员Value。我能想到的两种方式是:

第一:

    Byte1 Byte2 Byte3 Byte4 Byte5 Byte6 Byte7 Byte8
R =     A     0     0     0     V     0     0     0

第二:

    Byte1 Byte2 Byte3 Byte4
R =     A     V     0     0

谢谢!

【问题讨论】:

    标签: struct nested padding memory-alignment packing


    【解决方案1】:

    这个结构是这样打包的:

        Byte1 Byte2 Byte3 Byte4
    R =     A     V     0     0
    

    【讨论】:

      猜你喜欢
      • 2017-10-16
      • 2013-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多