如何使用包含结构的联合?

时间:2013-11-28 13:07:07

标签: c struct typedef unions

我有这个头文件和c文件:

code.h:

typedef struct types *someType;

typedef struct {
    int     thirdint;
    int     otherint; 
    int     someint; 
} thing, *Thing;

typedef union {
    otherthing  otherthing;
    thing thing;
} types;

code.c:

someType thestruct;

(thing)thestruct->someint = 1;

我认为这不会起作用,是吗?我被赋予此代码作为作业的一部分,并且不知道这是否导致我出错。

1 个答案:

答案 0 :(得分:2)

您的代码没有任何意义,它无效,我认为它不会编译。

没有必要尝试施放,只需访问您想要的成员:

thestruct->thing.someint = 1;

换句话说,你必须这样做,没有办法像你想象的那样使用演员。

如果你愿意,你当然可以计算指向正确成员的指针并使用它:

thing *thething = &thestruct->thing;
thething->someint = 1;

Unions基本上表现得像所有成员位于同一位置的结构,这是与union本身所在的位置相同(即从union的开头到每个成员的开头的偏移量为0,所有成员)。