如何使用Union在1 C数组中存储2个不同的结构
我想创建一个数组来存储2种类型的C结构 – Employee
,以及它的’child’, Manager
。 我创建了一个联合Person
来保存其中任何一个,然后尝试用它创建一个数组,但它不起作用。 我怎样才能让这样的arrays工作? 相关代码如下。
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(...);
我无法让下一行工作,我尝试了很多东西。
staff[3] = {boss, harry, tommy};
尝试:
staff[0].manager = boss; staff[1].employee = harry; /* ... */
或者可能:
Person staff [] = { {.manager = boss}, {.employee = harry}, /* ... */ };
但问问自己:如果staff[x]
是经理或仅仅是员工,您将如何知道?