How do i initialize a variable of structure B or C?
typedef struct _A
{
union
{
struct
{
int b;
} B;
struct
{
int c;
} C;
} u;
} A;
Something like
A.u.B *bVar; doesn't work
The typedef only covers A, not the union or structures defined therein.
typedef can't be nested like that - each user-defined "type" must have a single label, so a declaration of a variable of type A.u.B is illegal.
This should do it:
/* Initialise to zero */
A a = {{{0},{0}}};
/* Now set the b to 5 */
a.u.B.b = 5;
If you watch the curly brackets carefully, you will see that they exactly match the brackets in the type declaration. So the first brace begins A, the second begins A.u, the third begins A.u.B, and the first 0 corresponds to A.u.B.b. The close brace finishes A.u.B, then the comma means the next opening brace begins A.u.C, so the second zero initialises A.u.C.c, then all the braces close again.
Note anonymous structs may not be supported by all compilers. I cannot remember whether they are allowed by the standard or not...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With