I have written the following basic code for a menu:
typedef struct Menu {
char* title;
unsigned num_submenus;
struct Menu *submenu[];
} Menu;
Menu sub1 = {"Submenu 1", 0, {NULL}};
Menu sub2 = {"Submenu 2", 0, {NULL}};
Menu Main = {"Main Menu", 2, {&sub1, &sub2}}; /* No Error?! */
int main()
{
printf("%s\n", Main.title);
printf("%s\n", Main.submenu[0]->title);
printf("%s\n", Main.submenu[1]->title);
}
Browsing through a few related questions it seems like the only way to use a flexible array member is to dynamically allocate memory to it. However my compiler is perfectly happy to compile and run the code without any errors or warnings. Is this verboten?
I am using MinGW gcc 4.6.1 and compiling under C99 rules.
Initialization of flexible array member in this way is not allowed as per C standard.
21 EXAMPLE 2 After the declaration:
struct s { int n; double d[]; };the structure struct
shas a flexible array memberd. [...]22 Following the above declaration:
struct s t1 = { 0 }; // valid struct s t2 = { 1, { 4.2 }}; // invalid t1.n = 4; // valid t1.d[0] = 4.2; // might be undefined behaviorThe initialization of
t2is invalid (and violates a constraint) becausestruct sis treated as if it did not contain memberd. [...]
But, GCC allows the static initialization of flexible array:
Instead GCC allows static initialization of flexible array members. This is equivalent to defining a new structure containing the original structure followed by an array of sufficient size to contain the data. E.g. in the following,
f1is constructed as if it were declared likef2.struct f1 { int x; int y[]; } f1 = { 1, { 2, 3, 4 } }; struct f2 { struct f1 f1; int data[3]; } f2 = { { 1 }, { 2, 3, 4 } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With