【问题标题】:C: Array of structs in struct of arraysC:数组结构中的结构数组
【发布时间】:2012-08-25 13:04:58
【问题描述】:

我有这些结构:

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 中使用复杂的结构是可能的吗?

【问题讨论】:

  • 你是刚从 PHP 来的吗? :-)

标签: c arrays struct


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    struct Tmenu menu_test = {
        2,
        {
            "F1",
            2,
            {DATAFILE...},
            {DATAFILE2...}
        },
    

    应该是

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 也许您应该更改为struct struct_name[3] = {{init-list for 1},{init-list for 2},{init-list for 3}}; 然后编译器知道它必须期望 3 个结构。如果你不能固定结构的数量,那么你必须在其他次要初始化中中断初始化并在它们之间设置指针。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-29
      相关资源
      最近更新 更多