Reputation: 902
I'm trying to statically declare and initialize a structure array containing both char and int arrays.
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
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.
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 ?
Upvotes: 0
Views: 51
Reputation: 75062
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},
},
};
Upvotes: 2
Reputation: 5642
value
is not an array, but a pointer.
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.
Upvotes: 0