Reputation: 1473
I would like to create one array to store 2 types of C structs - Employee
, and its 'child', Manager
. I created a union Person
to hold either of them and then tried creating an array with it, but it doesn't work. How can I get such an array to work? The relevant code is below.
typedef struct {
char name[20];
double salary;
} Employee;
//Manager struct inheriting from employee struct
typedef struct {
Employee employee;
int bonus;
} Manager;
typedef union{
Employee e;
Manager m;
} Person;
Manager boss;
Employee harry ;
Employee tommy;
Person staff[];
int main(void)
{
...
boss = newManager(...);
harry = newEmployee(...);
tommy = newEmployee(...);
I couldn't get the next line to work, I tried many things.
staff[3] = {boss, harry, tommy};
Upvotes: 0
Views: 172
Reputation: 182649
Try:
staff[0].manager = boss;
staff[1].employee = harry;
/* ... */
Or maybe:
Person staff [] = {
{.manager = boss},
{.employee = harry},
/* ... */
};
But ask yourself: how will you know later if staff[x]
is a manager or a mere employee ?
Upvotes: 1