如何判断输出时使用的是什么类型的union?

how to determine what type of the union is used when output?

我在结构中使用联合类型来定义此人是学生还是员工。当我试图输出struct数组中的信息时,我发现很难弄清楚这个人是什么样的人,更不用说输出更多信息了。不要告诉我停止使用 union,对不起,我被要求这样做。 她是我的简化数据结构:

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

在 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];

然后您只需在分配结构时将其与联合一起设置即可。

了解 union 中存储的内容的唯一方法是将此信息包含在其他地方。

当您处理 union 数组(或包含 unionstruct 数组时,会发生两种常见情况:

  • 数组中的所有 union 都具有相同的类型,或者
  • 每个 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];