C:结合体内结构域的位置

我有以下类型:

union {
  struct {
    uint32_t c0;
    uint32_t k0[4];
    uint32_t c1;
    uint32_t v[2];
    uint32_t i[2];
    uint32_t c2;
    uint32_t k1[4];
    uint32_t c3;
  } named;
  uint32_t array[16];
} state;

因为“named”中的每个字段在初始化时都有意义,但之后我将主要用作字数组. C是否保证state.array [0]与state.named.c0相同,state.array [1]是state.named.k0 [0],依此类推?

如果没有,它的可能性有多大?如果我依赖它,是否有任何编译器/平台破坏我的代码?

最佳答案 为了回答你最令人担忧的问题,“……可能会起作用”,不要赌不可能,除非这是肯定的.它不是在这种情况下.

标准(第6.7.2.1节,第15页)规定结构的第一个成员或联合的所有成员的地址与结构或联合本身的地址相同.对您而言,这仅表示数组[16]的地址和命名相同,并且都等同于状态的地址.但是,如果没有依赖于实现的打包,则无法保证结构将精确覆盖,因为标准的相同部分要求可以进行结构间打包.

例如,无论出于何种原因,使用打包方案的编译器始终在64位边界上启动成员可以按如下方式布置您的名称:

struct {
    uint32_t c0;
    **padding 4 bytes**
    uint32_t k0[4];
    uint32_t c1;
    **padding 4 bytes**
    uint32_t v[2];
    uint32_t i[2];
    uint32_t c2;
    **padding 4 bytes**
    uint32_t k1[4];
    uint32_t c3;
    **padding 4 bytes**
} name;

简而言之,您可以保证的是,作为整体的名称占用的内存和您的并集的另一个成员所占用的内存,数组[16]将占用相同的内存,从每个开头的可开始可寻址位置开始.在名称包装的封面下,内存的样子取决于实施和您提供的任何包装提示.

标准的一些相关部分:

C99-§6.7.2.1,p6
As discussed in 6.2.5, a structure is a type consisting of a sequence of members, whose storage is allocated in an ordered sequence, and a union is a type consisting of a sequence of members whose storage overlap.

C99-§6.7.2.1,p15
Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

C99-§6.7.2.1,p16
The size of a union is sufficient to contain the largest of its members. The value of at most one of the members can be stored in a union object at any time. A pointer to a union object, suitably converted, points to each of its members (or if a member is a bit- field, then to the unit in which it resides), and vice versa.

C99-§6.7.2.1,p17
There may be unnamed padding at the end of a structure or union.

点赞