문제

I have this headerfile and c-file:

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;

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 (i.e. the offset from the start of the union to the start of each member is 0, for all members).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top