繁体   English   中英

为什么我不能打印出结构数组

[英]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 \

错误:段错误

我试过打印方法 printf("%.1f", Menu[0].subMenu[1]->id); 但它没有用,

我想打印出结构数组中的所有元素。

其他人已经指出了float id的问题,所以我建议您改用菜单和子菜单索引(按原样,结构,或者 @Fe2O3 指出映射到 integer,如unsigned id = m << 8 | sm )。 我将项目设为char *而不是固定大小,并将子菜单设为指向菜单的指针数组:

#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);
        }
    }
}

这是示例 output:

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

或者使用平面数组和unsigned char或枚举来指示级别:

#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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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