4

I have a struct that looks something like this:

typedef struct
{
    uint32_t a;
    uint32_t b;
    uint32_t c[5];
    uint32_t d;
} MY_STRUCT_T;

I want to initialize c, by name, to a non-zero value. I want everything else to be 0.

If c were not an array, I could do:

static MY_STRUCT_T my_struct = {.b = 1}; 

And I know I can do this:

static MY_STRUCT_T my_struct = {.c[0]=5,
    .c[1]=5,
    .c[2]=5,
    .c[3]=5,
    .c[4]=5};

but I was wondering if there was a more elegant syntax of which I am unaware: Something like:

static MY_STRUCT_T my_struct = {.c[] = {5,5,5,5,5}};

I have read the following, but they don't answer this question:
Initializing a struct to 0
Initialize/reset struct to zero/null
A better way to initialize a static array member of a class in C++ ( const would be preferred though )
How to initialize all members of an array to the same value?

Community
  • 1
  • 1
Frederick
  • 1,271
  • 1
  • 10
  • 29
  • Little difference between this and [How to initialize all members of an array to the same value](http://stackoverflow.com/q/201101/2410359) aside from the `.c=` part. – chux - Reinstate Monica Sep 12 '16 at 23:05

2 Answers2

3

So I wrote this question and then experimented for a while and found that the following would work:

static MY_STRUCT_T my_struct = {.c={5,5,5,5,5}};
Frederick
  • 1,271
  • 1
  • 10
  • 29
0

OP has 3 goals: 1) field array size is fixed width, 2) initialization like {7,7,7,7,7} is fixed width, 3) c to a non-zero value. As #1 and #2 have their sizes independent coded, 2 of the 3 goals can be met, but not all 3 - that is tricky.

What is to prevent/warn about MY_STRUCT_T my_struct = {.c = {5,5,5,5,5}}; not meeting goals should uint32_t c[5]; later become uint32_t c[6];? Nothing really.

Lacking a maintainable coding paradigm, consider this - copy one by one

Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • Yes, the summary is correct. That linked idea is not idea because I actually have to call that `for` loop code segment. – Frederick Sep 13 '16 at 18:12