Search code examples
cinitializationunions

How to initialise an anonymous union within a struct in c


I want to initialise all three arrays of mainstr , can anyone help me to initialise this anonymous union inside the struture? 0th index should initialise with interger array and 1st and 2nd indexes with char pointer.

typedef struct
{
   int testy;
   union
   {
      int a[3];
      char* b[3];
   }
   bool testz;
} testStr;


typedef struct
{
    testStr x[3];
} mainStr;

something like this,

mainStr test = {
                  {20, {{10, 20, 30}}, FALSE},
                  {10, {{"test1", "test2", NULL}}, TRUE},
                  {30, {{"test3", "test4", NULL}}, FALSE},
              }

Solution

  • Use designators:

    mainStr test = {{
                    {20, {{10, 20, 30}}, false},
                    {10, {.b={"test1", "test2", NULL}}, true},
                    {30, {.b={"test3", "test4", NULL}}, false},
                   }};
    

    Demo