[英]C: Array of structs in struct of arrays
我有以下結構:
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
錯誤消息的extra brace group at end of initializer
得到了extra brace group at end of initializer
。
我嘗試了許多不同的方法來完成此操作,但沒有一個成功。 那么,像這樣完全可以在C語言中使用復雜的結構嗎?
不,這種用法是不可能的,至少在“舊”(C89)C中是不可能的。不能使用結構文字來初始化指向所討論結構的指針 ,因為這不能解決結構在內存中的位置的問題位於。
struct Tmenu menu_test = {
2,
{
"F1",
2,
{DATAFILE...},
{DATAFILE2...}
},
應該
struct Tmenu menu_test = {
2,
{
"F1",
2,
{
{DATAFILE...},
{DATAFILE2...}
}
},
因為struct數組將放寬單括號的聲明。
問題是您聲明了一個指向結構的指針,但實際上您想要一個結構數組。 大多數時候, struct name*
和struct name[]
將是“可互換的”(請閱讀K&R,以了解它們不是同一件事),但是在靜態初始化的情況下,必須將其聲明為數組,以便編譯器可以期望將其聲明為數組。是固定大小的,因此可以確定用於該結構的內存量。
我需要改善答案,但是我的主要觀點是,我不會期望像int a* = {3,3,4,5};
編譯。 首先,分配雙方的類型都不同。 其次,編譯器如何知道它是數組的初始化列表而不是結構的初始化列表? 第三,如何知道應該期待4個元素而不是5個?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.