Page 1 of 1

Initializing a recursive structure

Posted: Tue Oct 31, 2023 5:36 am
by zhukovia
How can I initialize a recursive structure at the compilation stage?
Here is an example of the code

Code: Select all

struct menu_item {
    char name_menu[20];
    int level_menu;
    bool visible;
    struct menu_item *sub_menu[];
};
It doesn't work that way

Code: Select all

struct menu_item main_menu[] = { {"First item", 0, true, {}},
                                 {"Second item", 0, true, {}},
                                 {"The third item", 0, true, { {"First sub item", 0, true, {}},
                                                               {"Second sub item", 0, true, {}},
                                                               {"The third sub item", 0, true, {}},
                                                               {"Fourth sub item", 0, true, {}}
                                                             },
                                 {"Fourth item", 0, true, {}}
                                };

Re: Initializing a recursive structure

Posted: Tue Oct 31, 2023 8:04 am
by ESP_Sprite
This is an option:

Code: Select all

struct menu_item {
    char name_menu[20];
    int level_menu;
    bool visible;
    struct menu_item *sub_menu;
};

struct menu_item sub_menu[] =  { {"First sub item", 0, true, NULL},
                                {"Second sub item", 0, true, NULL},
                                {"The third sub item", 0, true, NULL},
                                {"Fourth sub item", 0, true, NULL} };

struct menu_item main_menu[] = { {"First item", 0, true, NULL},
                                 {"Second item", 0, true, NULL},
                                 {"The third item", 0, true, sub_menu},
                                 {"Fourth item", 0, true, NULL}
                                };


Note that you'd still need something (either a dummy menu item at the end of a menu, or an item count stored somwewhere) to let the rest of the code know the length of the (sub)menu. You probably also want to sprinkle some 'const' keywords through the declaration to make sure everything stays in flash rather than get copied to RAM.

Re: Initializing a recursive structure

Posted: Thu Nov 02, 2023 8:26 am
by zhukovia
Thanks for the answer, I did it :D