Code: Select all
#include
typedef struct {
uint16_t num_elements;
uint8_t elements[];
} HasArray;
HasArray x = {.num_elements = 2, .elements = {51, 17}};
HasArray y = {.num_elements = 4, .elements = {1, 42, 88, 73}};
const HasArray* collection[] = {&x, &y};
// main() somewhere
// HasArray cast is necessary so I can take the address, doing `&` on just the `{}`
// didn't work
// Also I would use a macro for these declarations, I know it's clunky
const HasArray* collection[] = {
&(HasArray){.num_elements = 2, .elements = {51, 17}},
&(HasArray){.num_elements = 4, .elements = {1, 42, 88, 73}}
};
< /code>
g ++ löscht < /p>
austest.c:16:56: error: non-static initialization of a flexible array member
16 | &(HasArray){.num_elements = 2, .elements = {51, 17}},
| ^
test.c:17:63: error: non-static initialization of a flexible array member
17 | &(HasArray){.num_elements = 4, .elements = {1, 42, 88, 73}}
| ^
< /code>
Was unterscheidet diese Situationen? In meinem Gehirn wird die zweite Syntax zur Kompilierungszeit immer noch Speicher zuweisen, aber es scheint, dass dies nicht der Fall ist. Ich verstehe Geben Sie die Größe dem Compiler an, ohne separate Variablen für jede Struktur zu erstellen?