如何确定输出时使用哪种类型的联合?

问题描述:

我在结构中使用了一个联合类型来定义这个人是学生还是职员。当我试图输出struct数组中的信息时,我发现很难找出这个人是什么类型的人,而不是输出更多的信息。不要告诉我停止使用工会,对不起,我被要求这样做。 赫斯是我的简单的数据结构:如何确定输出时使用哪种类型的联合?

typedef union student_or_staff{ 
    char *program_name; 
    char *room_num; 
}student_or_staff; 

typedef struct people{ 
    char *names; 
    int age; 
    student_or_staff s_or_s; 
}people[7]; 
+2

这不是'硬',这是不可能的。为'student_or_staff'添加一个标志来指示什么是什么。 – usr2564301

+0

你不能做这种开箱即用的东西。 – Linus

+0

如果你被告知要这样做,而这是一个练习,我会很好奇,看看有什么精确的指示 – Lovy

这是不可能做到这一点在C,但作为一种解决方法,你可以这样

enum { student_type, staff_type } PEOPLE_TYPE; 
typedef union student_or_staff{ 
char *program_name; 
char *room_num; 
}student_or_staff; 

typedef struct people{ 
char *names; 
int age; 
student_or_staff s_or_s; 
PEOPLE_TYPE people_type; 
}people[7]; 

然后你只需设置沿着你的工会添加类型与你的联合,当你分配你的结构。

+0

---------------------------- thanks -------------------- ------------- – NUO

要知道存储在union中的内容的唯一方法是将此信息包含在其他某个地方。

还有当你处理的union秒的阵列中发生两种常见的情况(或持有structunion):

  • 所有union S IN数组持有相同类型或
  • 每个union可以保持其自己的类型。

当阵列中的所有union都保持相同类型时,指示保持的类型为union的单个变量就足够了。

当每个union可以保持不同类型时,常用的方法是将其包装在struct中,并添加一个标志,指示设置union的方式。使用你的例子,该标志应该被添加到struct people,像这样:

enum student_staff_flag { 
    student_flag 
, staff_flag 
}; 
typedef struct people{ 
    char *names; 
    int age; 
    enum student_staff_flag s_or_s_flag; 
    student_or_staff s_or_s; 
}people[7]; 
+0

---------------------------- thanks ------- -------------------------- – NUO