[英]Static initialization of int array from within structure initialization
我正在嘗試靜態聲明和初始化一個包含 char 和 int 數組的結構數組。
下面的例子運行良好。
typedef struct myStruct
{
char* name;
uint8_t size;
uint8_t *value;
}myStruct;
uint8_t struct1_value[] = {0x00, 0x01};
uint8_t struct2_value[] = {0x00, 0x01, 0x03, 0x04};
myStruct myStructArray[] = {
[0] = {
.name = "Struct_1",
.size = 2,
.value = struct1_value,
},
[1] = {
.name = "Struct_2",
.size = 4,
.value = struct2_value,
},
};
我找不到允許直接從myStructArray
初始化value
字段的語法
我想知道是否有一種方法可以在不必聲明struct1_value
和struct2_value
變量的情況下初始化value
字段。
也許這在純 C 中是不可能的,但是因為可以靜態初始化一個char
數組,為什么不使用int
數組呢?
您可以使用復合文字。
myStruct myStructArray[] = {
[0] = {
.name = "Struct_1",
.size = 2,
.value = (uint8_t[]){0x00, 0x01},
},
[1] = {
.name = "Struct_2",
.size = 4,
.value = (uint8_t[]){0x00, 0x01, 0x03, 0x04},
},
};
value
不是數組,而是指針。 您必須通過引用其他地方存在的數組來初始化它。
實際上name
工作方式不同,因為"like this"
字符串的詞法文字語法創建了一個未命名的字符數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.