How can I access the union members which exist inside the structure?
Consider the code snippet:
struct Emp {
char name[20];
union address {
char addr[50];
};
};
struct Emp e;
Using e
, how do I access the addr
type without creating any union object?
Unnamed struct/union fields within structs/unions is supported in C11 and also GCC extension. If this feature is on, you can use
e.addr
directly. Note that the tag name should be empty, either.If it's not supported, you need to give the
union
a name and usee.u.addr
.Union should be named first and then access as
Here,
address it as
Give the union member a name:
Now you can access it like so: