Union - 您如何知道正在使用哪个union参数?

时间:2013-12-01 11:24:07

标签: c unions

我有以下代码:

struct sched_param {
    union {
        int sched_priority;
        struct rcost_sched_param rcost_params;
    };
};

我想知道这两个参数中哪一个是“活跃的”。除了在struct sched_param

中添加int之外,我有没有办法做到这一点

2 个答案:

答案 0 :(得分:5)

struct sched_param {
  int type;
  union {
       int sched_priority;
        struct rcost_sched_param rcost_params;
  };
}

您可以添加名为type的成员,保存参数为“活动”的数据

答案 1 :(得分:3)

不,这是棘手的部分:您必须存储要使用的联合条目的信息(例如,使用单个char成员)。另请注意,两个联合条目可能不一定指向相同的位置(例如由于打包或字节顺序),因此您不能只读取一个值并确定它是否包含有效值,因为它是直到编译器如何在幕后的union中实现struct。