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.
struct Emp {
char name[20];
union {
char addr[50];
};
};
If it's not supported, you need to give the union
a name and use e.u.addr
.
struct Emp {
char name[20];
union address {
char addr[50];
} u;
};
Give the union member a name:
struct Emp {
char name[20];
union {
char addr[50];
} address;
};
Now you can access it like so:
struct Emp e;
e.address.addr;
Union should be named first and then access as
[struct_object_name].[union_name].[union_datamember]
Here,
struct Emp {
char name[20];
union {
char addr[50];
} Emp_address;
};
struct Emp e;
address it as
e.Emp_address.addr