arrayscinitializationstructureunions

Error while initializing the union of struct member in c


I have a struct like this -

struct ArrayAdv{
        int size;
        int length;
        union{
                struct{
                        int *A;
                } dynamic;
                struct{
                        int A[20];
                } stat;
        } item;

};

And I am getting error when I am trying to initialize the array -

Error I am encountered with

I am trying to initialize the array like this -

struct ArrayAdv arrAdv;
arrAdv.item.stat.A = {33, 2, 7, 88, 35, 90, 102, 23, 81, 97};

And getting the error which, I have mentioned, I want it to be initialized correctly.


Solution

  • You're getting an error because you're not actually initializing, but assigning, and you can't assign to an array. An initialization happens at the time a variable is defined.

    What you're looking for is:

    struct ArrayAdv arrAdv = 
        { .item = { .stat = { .A = { 33, 2, 7, 88, 35, 90, 102, 23, 81, 97 } } } };