简体   繁体   English

从结构初始化中静态初始化 int 数组

[英]Static initialization of int array from within structure initialization

I'm trying to statically declare and initialize a structure array containing both char and int arrays.我正在尝试静态声明和初始化一个包含 char 和 int 数组的结构数组。

The following example works well.下面的例子运行良好。

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,
    },
};

I can't find a syntax that allows to initialize value field directly from myStructArray我找不到允许直接从myStructArray初始化value字段的语法

I would like to know if there is a way to initialize the value field without having to declare struct1_value and struct2_value variables.我想知道是否有一种方法可以在不必声明struct1_valuestruct2_value变量的情况下初始化value字段。

Maybe it's just not possible in pure C but as it's possible to statically initialize a char array, why not with a int array ?也许这在纯 C 中是不可能的,但是因为可以静态初始化一个char数组,为什么不使用int数组呢?

You can use compound literals .您可以使用复合文字

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 is not an array, but a pointer. value不是数组,而是指针。 You must initialize it by referring to the array that exists elsewhere.您必须通过引用其他地方存在的数组来初始化它。

Indeed name works differently because the lexical literal syntax for strings "like this" create an unnamed array of chars.实际上name工作方式不同,因为"like this"字符串的词法文字语法创建了一个未命名的字符数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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