Home > Software engineering >  How to define and initialize C structure containing structure arrays
How to define and initialize C structure containing structure arrays

Time:10-20

I have main structure which is containing 2 arrays of another structures. I am using it in code as constant so I would like to initialize it in advance. How would I do it correctly? This is my example, it throws milion warnings and obviously doesn't work.

#include <stdio.h>

typedef struct{
    char a;
    char b;
} subStruct1;

typedef struct{
    char c;
    char d;
}subStruct2;

typedef struct{
    subStruct1 *SS1;
    subStruct2 *SS2;
} mainStruct;

mainStruct MS = {
    SS1: {{'a', 'b'}, {'A', 'B'}},
    SS2: {{'c', 'd'}, {'C', 'D'}}
};

int main()
{
    printf("%c %c %c",MS.SS1[0].a,MS.SS1[1].b,MS.SS2[1].c);
    return 0;
}

CodePudding user response:

You can't use an array initializer to initialize a pointer. You can however use a compound literal with array type:

mainStruct MS = {
    .SS1 = (subStruct1 []){{'a', 'b'}, {'A', 'B'}},
    .SS2 = (subStruct2 []){{'c', 'd'}, {'C', 'D'}}
};

This creates two array objects and initializes the two pointers to point to the first element of each.

Also note that the syntax for a designated initializer is ".field=", not "field:"

  • Related