Can I 'extend' a struct in C?

后端 未结 7 1493
太阳男子
太阳男子 2020-12-08 16:05
typedef struct foo_s {
    int a;
} foo;

typedef struct bar_s {
    foo;
    int b;
} bar;

Essentially I want to do:

bar b;
b.a;
<         


        
7条回答
  •  余生分开走
    2020-12-08 16:44

    If you ment

    typedef struct foo_s {
        int a;
      } foo;
    
    typedef struct bar_s {
     foo my_foo;
    int b;
    } bar;
    

    so you can do:

    bar b; b.my_foo.a = 3;
    

    Otherwise, There's no way of doing it in C since the sizeof(bar_s) is detriment on compile time. It's not a good practice but you can save a void * ptr; pointer within bar_s, and another enum which describes the ptr type, and cast by the type.

    i.e:

    typedef enum internalType{
      INTERNAL_TYPE_FOO = 0,
    }internalType_t;
    
    typedef struct bar_s {
     internalType_t ptrType;
     void* ptr;
    int b;
    } bar;
    

    and then:

    bar b;  foo f;
    b.ptrType = INTERNAL_TYPE_FOO;
    b.ptr = &f;
    

    and some where else in the code:

     if (b.ptrType == INTERNAL_TYPE_FOO) {
        foo* myFooPtr = (foo *)b.ptr;
     }
    

提交回复
热议问题