代码之家  ›  专栏  ›  技术社区  ›  Juan Leni

对联合数据的原始访问

c
  •  0
  • Juan Leni  · 技术社区  · 6 年前

    例如(有点人为,但我希望它传达了我的想法),如果我改变其他类型的外观,我不想调整原始的大小:

    #pragma pack(push, 1)
    typedef union {
      uint8_t raw[0];
      struct {
        uint8_t bar[32];
        othertype_t foo[4];
      };
    } sometype_t;
    #pragma pack(pop)
    

    以后我可以做 sizeof(union sometype_t) raw .

    使用raw[0]可以工作,但我知道这是gcc的非标准扩展。我怎么能用一种更便携的方式做到这一点?

    作为一个“诡计”,我可以像 raw[1] 但感觉有点误导。

    有人指出这是C++中未定义的行为。你能提供一些关于这个的附加信息吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   0___________    6 年前

    也许 吧

    typedef union 
    {
      struct _struct
      {
        uint8_t bar[32];
        othertype_t foo[4];
      };
      uint8_t raw[sizeof(struct _struct)];
    } sometype_t;