[英]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. 我想按名称将
c
初始化为非零值。 I want everything else to be 0. 我希望其他一切都是0。
If c
were not an array, I could do: 如果
c
不是数组,我可以这样做:
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 将结构初始化为0
Initialize/reset struct to zero/null 将struct初始化/重置为零/ null
A better way to initialize a static array member of a class in C++ ( const would be preferred though ) 在C ++中初始化类的静态数组成员的更好方法(虽然const是首选)
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. OP有3个目标:1)字段数组大小是固定宽度,2)初始化如
{7,7,7,7,7}
是固定宽度,3) c
是非零值。 As #1 and #2 have their sizes independent coded, 2 of the 3 goals can be met, but not all 3 - that is tricky. 由于#1和#2的大小是独立编码的,因此可以满足3个目标中的2个,但不是全部3个 - 这很棘手。
What is to prevent/warn about MY_STRUCT_T my_struct = {.c = {5,5,5,5,5}};
什么是预防/警告
MY_STRUCT_T my_struct = {.c = {5,5,5,5,5}};
not meeting goals should uint32_t c[5];
不应该达到目标
uint32_t c[5];
later become uint32_t c[6];
后来成为
uint32_t c[6];
? ? Nothing really.
真的没什么。
Lacking a maintainable coding paradigm, consider this - copy one by one 缺乏可维护的编码范例,请考虑这一点 - 逐个复制
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.