Home > Enterprise >  Is there a quick way to initialise a struct array with the same attributes?
Is there a quick way to initialise a struct array with the same attributes?

Time:05-30

struct child {
    char name[32];
    int height;
};

struct child group_a[8];

I'd like to initialise every child in group_a with the same name and height, for example name = "XXX" and height = "100".

Is there a quick of doing it, rather than struct child group_a[8] = {{"XXX", 100}, {"XXX", 100}, ..., {"XXX", 100}}?

CodePudding user response:

Try using compound literals like this:

int i = 8;
while(i--)
   group_a[i] = (struct child) { "XXX", 100 };

CodePudding user response:

Maybe a bit lame, but why not use a macro?

#define H {"XXX", 100}

struct child group_a[8] = {H, H, H};

CodePudding user response:

It cannot be done in standard C without deeper preprocessor magic. However there is an extension for ranges in designated initializers. It is supported by main compilers (GCC, CLANG, Intel).

struct child group_a[] = {
  [0 ... 7] = { .name = "XXX", .height = 100 }
};
  • Related