Struct pointer compatibility

后端 未结 6 2221
攒了一身酷
攒了一身酷 2020-12-11 03:13

Suppose we have two structs:

typedef struct Struct1
{
    short a_short;
    int id;
} Struct1;

typedef struct Struct2
{
    short a_short;
    int id;
             


        
6条回答
  •  庸人自扰
    2020-12-11 03:19

    No, the standard does't allow this; accessing the elements of a Struct2 object through a Struct1 pointer is undefined behavior. Struct1 and Struct2 are not compatible types (as defined in 6.2.7) and may be padded differently, and accessing them via the wrong pointer also violates aliasing rules.

    The only way something like this is guaranteed to work is when Struct1 is included in Struct2 as its initial member (6.7.2.1.15 in the standard), as in unwind's answer.

提交回复
热议问题