Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I 'extend' a struct in C?

Tags:

c

struct

typedef struct foo_s {
    int a;
} foo;

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

Essentially I want to do:

bar b;
b.a;

I know that i could do b.foo_name.a if I had named the foo struct in bar, but Id prefer not to.

Any way to do this?

This question has gotten a variety of different answers, so let me explain the need. The reason I want to do this is because I have a library which I need to adapt to my situation, meaning that I cant modify the original struct decleration. Furthermore, all I need to do is add 1 item to the beginning of the struct (why the beginning? because I have an 'object' struct which heads all the structs in the project). I could simply embed the struct like you mention but its REALLY annoying as all references will need to be typed 'variable->image.location' that 'image.' typed a billion types is really annoying.

like image 815
chacham15 Avatar asked Sep 10 '11 08:09

chacham15


2 Answers

Evidently this feature has been added to C11, but alas I don't have access to a C compiler of recent vintage (>= GCC 4.6.2).

typedef struct foo {
  int a;
} foo;

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

int main() {
  bar b;
  b.a = 42;
  b.b = 99;
  return 0;
}
like image 158
wcochran Avatar answered Oct 18 '22 05:10

wcochran


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

#include <stdlib.h>
#include <stdio.h>

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;
}
like image 24
Jouni K. Seppänen Avatar answered Oct 18 '22 06:10

Jouni K. Seppänen