Struct pointer compatibility

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

    Yes, it is ok to do that!

    A sample program is as follows.

    #include 
    
    typedef struct Struct1
    {
        short a_short;
        int id; 
    } Struct1;
    
    typedef struct Struct2
    {
        short a_short;
        int id; 
        short another_short;
    } Struct2;
    
    int main(void) 
    {
    
        Struct2 s2 = {1, 2, 3}; 
        Struct1 *ptr = &s2;
        void *vp = &s2;
        Struct1 *s1ptr = (Struct1 *)vp;
    
        printf("%d, %d \n", ptr->a_short, ptr->id);
        printf("%d, %d \n", s1ptr->a_short, s1ptr->id);
    
        return 0;
    }
    

提交回复
热议问题