如何在指针数组中声明三级指针

3
如何声明一个三级指针,其中包含指针数组,就像我所拥有的一样。
char *mainmenu[] = {"menu1", "menu2", "menu3"}

请看图片:

alt text

如何将我的菜单1、2、3与图片中的m1p1、m2p1连接起来?请帮我提供语法,谢谢。


你可以嵌套数组,但需要明确指定除一个维度外的所有维度。 - sbi
3个回答

2

all[0] 的类型是 char **,并且与您定义的 mainmenu 匹配,尽管它在数组中出现了终止的 NULL

char ***all;
char *mainmenu[] = {"menu1", "menu2", "menu3", NULL};
all[0] = mainmenu;

这是涉及到你所提供的图片中类型的模型,而不是逐字翻译的解决方案。如果您需要数据结构的相关内容,请参考C编程教程! - Matt Joiner

1

你可以使用多个*或者多组括号。根据你描述的数据结构,我会选择
char *mainmenu[X][Y] = {{"m1p1", "m1p2", "m1p3"}, {"m2p1", "m2p2"}}
注意必须定义Y的长度。在C语言中的多维数组中,除了最外层的维度(如果你用数据初始化),其他所有维度都必须定义长度。


0

这可能比你要求的多,但应该很有帮助:

/* Functions associated to menu items */
void M1P1() { puts("Hey! You selected menu 1 position 1!"); }
void M1P2() { puts("Hey! You selected menu 1 position 2!"); }
void M1P3() { puts("Hey! You selected menu 1 position 3!"); }
void M2P1() { puts("Hey! You selected menu 2 position 1!"); }
void M2P2() { puts("Hey! You selected menu 2 position 2!"); }
// ...

/* structure describing single sub-menu item */
typedef struct {
    char *caption; // item caption
    void (*action)(); // function associated to this item
} SubMenuItem;

/* array of all sub-menu items of menu1 */
SubMenuItem sub_menu1[] = {
    { "m1p1", M1P1 },
    { "m1p2", M1P2 },
    { "m1p3", M1P3 },
};
/* array of all sub-menu items of menu2 */
SubMenuItem sub_menu2[] = {
    { "m2p1", M2P1 },
    { "m2p2", M2P2 },
};
// ...

/* structure describing single main-menu item */
typedef struct {
    char *caption; // item caption
    SubMenuItem *sub_menus; // array of sub-menu items
    unsigned sub_menus_count; // number of sub-menu items (length of the array)
} MenuItem;

/* array of all main-menu items */
MenuItem menu[] = {
    { "menu1", sub_menu1, sizeof(sub_menu1) / sizeof(sub_menu1[0]) },
    { "menu2", sub_menu2, sizeof(sub_menu2) / sizeof(sub_menu2[0]) },
    // ...
};

/* number all main-menu items */
#define MENU_ITEMS_COUNT (sizeof(menu) / sizeof(menu[0]));


/* Example - iterationg menu */
int i, j;
for (i = 0; i < MENU_ITEMS_COUNT; i++) { // iterate through main-menu items
    printf("%d) %s\n", i + 1, menu[i].caption); // print main-menu item index and caption
    for (j = 0; j < menu[i].sub_menus_count; j++) { // iterate through sub-menu items of current main-menu item
        printf("\t%d.%d) %s\n", i + 1, j + 1, menu[i].sub_menus[j].caption); // print indices and sub-menu item caption
    }
}

putchar('\n');

/* Example - running action associated to menu item */
/* To run action associeted to menu 1 position 2 */
menu[0].sub_menus[1].action();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接