简体   繁体   中英

Why can't I print out array of struct


struct Menu
{
    float id;
    char item[50];
    struct Menu* subMenu[10];
} Menu[5] = {
    {1, "SEARCH YOUR CONTACT", (struct Menu[]){{1.1, "ADD TO FAVOURITES"}, {1.2, "UPDATE"}, {1.3, "DELETE"}, {1.4, "ADD FIELD"}, {1.5, "BACK TO MAIN MENU"}}},
    {2, "ADD CONTACT"},
    {3, "DISPLAY FAVOURITES CONTACT", (struct Menu[]){{3.1, "ADD TO FAVOURITES"}, {3.2, "UPDATE"}, {3.3, "DELETE"}, {3.4, "ADD FIELD"}, {3.5, "BACK TO MAIN MENU"}}},
    {4, "DISPLAY ALL CONTACT", (struct Menu[]){{4.1, "ADD TO FAVOURITES"}, {4.2, "UPDATE"}, {4.3, "DELETE"}, {4.4, "ADD FIELD"}, {4.5, "BACK TO MAIN MENU"}}},
    {5, "EXIT APPLICATION"}
};
void menuItem()
{
    for (int i = 0; i < 5; i++)
    {
        printf(" ... %.1f \\", Menu[0].subMenu[i]->id);
    }
}

output: ... 1.1 \

Error: segmention fault

I tried printing method printf("%.1f", Menu[0].subMenu[1]->id); but it didn't work,

I want to print out of all elements in the array of struct.

Others already pointed out the problem with float id so I suggest you use a menu and submenu indices instead (either as is, a struct, or as @Fe2O3 pointed out mapped into an integer like unsigned id = m << 8 | sm ). I made item a char * instead of fixed size and the sub-menu an array of pointers to Menu:

#include <stdio.h>

struct Menu {
    char *item;
    struct Menu **subMenu;
} Menu[] = {
    {"SEARCH YOUR CONTACT", (struct Menu *[]) {
        &(struct Menu) {"ADD TO FAVORITES"},
        &(struct Menu) {"UPDATE"},
        &(struct Menu) {"DELETE"},
        &(struct Menu) {"ADD FIELD"},
        &(struct Menu) {"BACK TO MAIN MENU"},
        NULL
    }},
    {"ADD CONTACT", NULL},
};

int main() {
    for (int m = 0; m < sizeof Menu / sizeof *Menu; m++) {
        printf("item: %s\n", Menu[m].item);
        for(int sm = 0;  Menu[m].subMenu && Menu[m].subMenu[sm]; sm++) {
            printf("  item: %s\n", Menu[m].subMenu[sm]->item);
        }
    }
}

Here is the example output:

item: SEARCH YOUR CONTACT
  item: ADD TO FAVORITES
  item: UPDATE
  item: DELETE
  item: ADD FIELD
  item: BACK TO MAIN MENU
item: ADD CONTACT

Alternatively use a flat array and an unsigned char or enum to indicate the level:

#include <stdio.h>

struct Menu {
    unsigned char level;
    char *item;
} Menu[] = {
    {0, "SEARCH YOUR CONTACT"},
    {1, "ADD TO FAVORITES"},
    {1, "UPDATE"},
    {1, "DELETE"},
    {1, "ADD FIELD"},
    {1, "BACK TO MAIN MENU"},
    {0, "ADD CONTACT"},
};

int main() {
    for(int m = 0; m < sizeof Menu / sizeof *Menu; m++) {
        printf("%*s%sitem: %s\n", 2 * Menu[m].level, "", Menu[m].item);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM