0

我有这些结构:

struct menu_item{
    int id;
    char *text;
};

struct menu_tab{
    char *label;
    unsigned char item_count;
    struct menu_item *items;
};

struct menu_page{
    char *label;
    unsigned char tab_count;
    struct menu_tab *tabs;
};

struct Tmenu{
    unsigned char page_count;
    struct menu_page *pages;
};

我想定义整个菜单系统:

struct Tmenu menu_test = {
    2,
    {
        "F1",
        2,
        {
            {
                "File",
                8,
                {
                    {1, "text  1"},
                    {2, "text2"},
                    {3, "text3333333"},
                    {4, "text4"},
                    {5, "Hello"},
                    {6, "42"},
                    {7, "world"},
                    {8, "!!!!!!!!"}
                }

            },
            {
                "File2",
                3,
                {
                    {11, "file2 text  1"},
                    {12, "blah"},
                    {13, "..."}
                }

            }
        }
    },
    {
        "F2",
        1,
        {
            {
                "File3",
                5,
                {
                    {151, "The Answer To Life"},
                    {152, "The Universe"},
                    {153, "and everything"},
                    {154, "iiiiiiiiiiiiiiiis"},
                    {42, "Fourty-Two"}
                }

            }
        }
    }
};

但是当我尝试编译时,我收到 extra brace group at end of initializer错误消息。

我尝试了许多不同的方法来做到这一点,但没有一个成功。那么像这样在C中使用复杂的结构是可能的吗?

4

3 回答 3

1

不,这种用法是不可能的,至少在“旧”(C89)C中是不可能的。结构文字不能用于初始化指向相关结构的指针,因为这不能解决结构在内存中的位置的问题位于。

于 2012-08-25T13:16:41.630 回答
0
struct Tmenu menu_test = {
    2,
    {
        "F1",
        2,
        {DATAFILE...},
        {DATAFILE2...}
    },

应该

struct Tmenu menu_test = {
    2,
    {
        "F1",
        2,
        {
        {DATAFILE...},
        {DATAFILE2...}
        }
    },

因为 struct 数组将丢失单大括号的声明。

于 2012-08-25T13:23:10.137 回答
0

问题是您声明了一个指向结构的指针,但实际上您想要一个结构数组。大多数时候struct name*并且struct name[]将是“可互换的”(阅读 K&R 以了解它们不是同一件事),但在静态初始化的情况下,它必须声明为一个数组,以便编译器可以预期它是固定大小的,因此它可以确定要用于结构的内存量。

我需要改进我的答案,但我的主要观点是我不希望像int a* = {3,3,4,5};编译这样的东西。首先,赋值两边的类型不同。其次,编译器如何知道它是数组的初始化列表而不是结构?第三,它怎么知道它应该期望 4 个元素而不是 5 个?

于 2012-08-25T13:24:09.010 回答