Can I 'extend' a struct in C?

后端 未结 7 1467
太阳男子
太阳男子 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:36

    You can, using pointers, because a pointer to a structure object is guaranteed to point its first member. See e.g. this article.

    #include 
    #include 
    
    typedef struct foo_s {
        int a;
    } foo;
    
    typedef struct bar_s {
        foo super;
        int b;
    } bar;
    
    int fooGetA(foo *x) {
      return x->a;
    }
    
    void fooSetA(foo *x, int a) {
      x->a = a;
    }
    
    int main() {
      bar* derived = (bar*) calloc(1, sizeof(bar));
      fooSetA((foo*) derived, 5);
      derived->b = 3;
      printf("result: %d\n", fooGetA((foo*) derived));
      return 0;
    }
    

提交回复
热议问题