Initializing a recursive structure

zhukovia
Posts: 7
Joined: Tue Oct 31, 2023 5:25 am

Initializing a recursive structure

Postby zhukovia » Tue Oct 31, 2023 5:36 am

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

ESP_Sprite
Posts: 9730
Joined: Thu Nov 26, 2015 4:08 am

Re: Initializing a recursive structure

Postby ESP_Sprite » Tue Oct 31, 2023 8:04 am

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.

zhukovia
Posts: 7
Joined: Tue Oct 31, 2023 5:25 am

Re: Initializing a recursive structure

Postby zhukovia » Thu Nov 02, 2023 8:26 am

Thanks for the answer, I did it :D

Who is online

Users browsing this forum: Gaston1980 and 119 guests