简体   繁体   English

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

[英]How do I use unions containing structs?

I have this headerfile and c-file: 我有这个头文件和c文件:

code.h: 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: code.c:

someType thestruct;

(thing)thestruct->someint = 1;

I do not think that this will work, does it? 我不认为这会起作用,是吗? I was given this code as a part of an assignment and don't know if this is causing me an error or not. 我被赋予这个代码作为一个任务的一部分,不知道这是否导致我错误。

Your code doesn't make any sense, it's not valid and I don't think it will compile. 你的代码没有任何意义,它是无效的,我不认为它会编译。

There is no need to try to cast, just access the member you want: 没有必要尝试强制转换,只需访问您想要的成员:

thestruct->thing.someint = 1;

In other words, you must do it like this, there is no way to do this with a cast like you attempted. 换句话说,你必须这样做,没有办法像你试图的演员那样做。

You can of course compute a pointer to the proper member and work with that, if you want: 您当然可以计算指向正确成员的指针并使用它,如果您需要:

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

Unions basically behave like structs where all the members are located at the same place, which is the same location as the union itself is located at (ie the offset from the start of the union to the start of each member is 0, for all members). 联合基本上表现得像结构,其中所有成员都位于同一个地方,这是与联盟本身所在的位置相同(即,从联盟开始到每个成员的开头的偏移为0,对于所有成员)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM