4

我可以检查c中的联合是否为空吗?例如:

union{ char * name, struct Something * something ... }someUnion;

有没有办法检查是否没有元素被初始化,而不做元素虎钳检查?

谢谢。

4

2 回答 2

6

不,不是没有为此目的添加特定标志。例如:

struct someStruct {
    int initialized;
    union {
        char *name;
        struct Something *something;
    };
};

您甚至可以存储一个标志来代替initialized指示联合包含哪种数据的标志。这通常称为标记联合

于 2012-05-10T22:15:49.077 回答
1

是的,在联合的所有成员都是指针类型或整数类型的条件下,并且初始化意味着已分配了一个非 NULL 的值,检查一个元素是否为 NULL 就足够了。

union { 
    char * name;
    struct Something * something; } someUnion;

if (someUnion.name != 0) {
    // here you know that someUnion.something is not NULL too.
    // You don't know if it has been initialized as char*
    // or as struct something* though. Presumeably since
    // it is a unionboth interpretations make some sense. 
}
于 2012-05-10T22:35:55.293 回答