简体   繁体   中英

Initializing an array member of a struct by name

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?

所以我写了这个问题,然后进行了一段时间的实验,发现以下内容可行:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM