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.
Not possible in
C
the way you did. But you can mimic inheritance having afoo
member variable inbar
.If you ment
so you can do:
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 avoid * ptr;
pointer within bar_s, and another enum which describes theptr
type, and cast by the type.i.e:
and then:
and some where else in the code:
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).
You can, using pointers, because a pointer to a structure object is guaranteed to point its first member. See e.g. this article.
You can try using inheritance:
Works in C++, not sure if it works in C.
It can be easily done via preprocessor:
Create a file named
base_foo.h
:Then simply include it: