Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Struct inside union inside struct

Tags:

c

struct

unions

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

like image 855
Nitrate Avatar asked Dec 28 '22 01:12

Nitrate


2 Answers

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.

like image 73
Alnitak Avatar answered Jan 13 '23 02:01

Alnitak


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...

like image 42
Ben Avatar answered Jan 13 '23 03:01

Ben