Can I inherit a structure in C? If yes, how?
A slight variation to the answer of anon (and others' similar). For one level deep inheritance one can do the following:
#define BASEFIELDS \
char name[NAMESIZE]; \
char sex
typedef struct {
BASEFIELDS;
} Person;
typedef struct {
BASEFIELDS;
char job[JOBSIZE];
} Employee;
typedef struct {
BASEFIELDS;
Employee *subordinate;
} Manager;
This way the functions accepting pointer to Person, will accept pointer to Employee or Manager (with casting), same as in other answers, but in this case the initialisation will be natural as well:
Employee e = {
.name = "...";
...
};
vs
# as in anon's answer
Employee e = {
.person.name = "...";
...
};
I believe this is how some popular projects do that (eg. libuv)
UPDATE: also there are some good examples of similar (but not the same) concept in libsdl events implementation using structs and unions.