Say I have the following types:
typedef struct TYPEA
{
int type;
char[12] id;
} TYPEA;
typedef struct TYPEB
{
int type;
int value;
} TYPEB;
I want to use create a union of these types and 'int', so that I can access the "type" int without needing to know whether TYPEA or TYPEB is stored in the union (the value of int lets me determine which is actually stored there). I can't get the right syntax though.
My union:
typedef union MEMBER
{
int type;
struct TYPEA a;
struct TYPEB b;
} MEMBER;
The union is accessed via:
typedef struct WRAPPER
{
union MEMBER* member;
struct WRAPPER* next;
} WRAPPER;
Questions:
- (With 'w' as a pointer to an allocated WRAPPER struct) Accessing using
w->member->a.id
gives "request for member 'id' in something not a structure or union. - Can I assign a pointer to an already malloc'd TYPEA/B to w->member directly? Or does a union need to be malloced specially?
Thanks.
You might want to check out the code in my question:
Union of structs with common first member
Essentially, I do what you want but I'm using an inner struct (
contained
in the example) that's common to the two types. This struct can then be cast to gain access to the common elements of both types.member
field as a pointer, so you should usew->member->type
instead ofw->member.type
.malloc
the union type. When you allocate a union, you'll get a structure that has asizeof
equal to the largest element in the union. If you try to copy structures into union pointers, you'll mess up the alignment.w->member.type
should bew->member->type
becausew->member
is a pointer.I don't know off the top of my head whether C will let you assign a
TYPEA*
orTYPEB*
to aMEMBER*
- somehow I doubt it. You can always(MEMBER*)
it, but I would consider recomposing thestruct
s to remove theint
tag and instead declare onestruct
that includes the tag and aunion
ofTYPEA
andTYPEB
. Thestruct
s ideally shouldn't need to be concerned with the fact that they're in aunion
.w->member->type
.union
specifically.One note that may be a point of misunderstanding is that the
union
holds EITHER theint
, orTYPEA
, orTYPEB
, so in particular you cannot rely on yourint type;
in the union to tell you whichstruct
the union holds.Edit to respond to question in comments:
You probably want something like this: