Struct pointer compatibility

后端 未结 6 2230
攒了一身酷
攒了一身酷 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:33

    It is safe, as far as I know.

    But it's far better, if possible, to do:

    typedef struct {
        Struct1 struct1;
        short another_short;
    } Struct2;
    

    Then you've even told the compiler that Struct2 starts with an instance of Struct1, and since a pointer to a struct always points at its first member, you're safe to treat a Struct2 * as a Struct1 *.

提交回复
热议问题