1

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;
}
andz
  • 274
  • 1
  • 3
  • 12

1 Answers1

5

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:"

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 1
    `field:` is GNU field designator extension which has been [obsoleted since GCC 2.5](https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html). – H.S. Oct 19 '21 at 17:19
  • @dbush Thank you, I was searching how to to it over an hour. Okej, I will stick to ".field=" initializer. – andz Oct 19 '21 at 17:26