我有一个看起来像这样的结构:
typedef struct
{
uint32_t a;
uint32_t b;
uint32_t c[5];
uint32_t d;
} MY_STRUCT_T;
我想按名称将 c
初始化为非零值 . 我希望其他一切都是0 .
如果 c
不是数组,我可以这样做:
static MY_STRUCT_T my_struct = {.b = 1};
而且我知道我可以这样做:
static MY_STRUCT_T my_struct = {.c[0]=5,
.c[1]=5,
.c[2]=5,
.c[3]=5,
.c[4]=5};
但我想知道是否有更优雅的语法我不知道:类似于:
static MY_STRUCT_T my_struct = {.c[] = {5,5,5,5,5}};
我已阅读以下内容,但他们没有回答这个问题:
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?
2 回答
所以我写了这个问题,然后进行了一段时间的实验,发现以下内容可行:
OP有3个目标:1)字段数组大小是固定宽度,2)初始化像
{7,7,7,7,7}
是固定宽度,3)c
到非零值 . 由于#1和#2的大小是独立编码的,因此可以满足3个目标中的2个,但不是全部3个 - 这很棘手 .什么是预防/警告
MY_STRUCT_T my_struct = {.c = {5,5,5,5,5}};
不符合目标uint32_t c[5];
后来成为uint32_t c[6];
?真的没什么 .缺乏可维护的编码范例,请考虑this - copy one by one