简体   繁体   中英

How to use a Union to store 2 different structs in 1 C array

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};

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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM