問題:以下代碼片段編譯良好(其中兩種結構型別都是 typedefed):
typedef struct {
int a;
float b;
} member_struct;
typedef struct {
int a;
double b;
member_struct c;
} outside_struct;
outside_struct my_struct_array[4];
但是,如果洗掉“outside_struct”的 typedef:
typedef struct {
int a;
float b;
} member_struct;
struct {
int a;
double b;
member_struct c;
} outside_struct;
struct outside_struct my_struct_array[4];
我收到錯誤:
"array type has incomplete element type 'struct outside_struct'".
如果我也洗掉“member_struct”的 typedef,我會收到一個額外的錯誤:
"field 'c' has incomplete type"
問題:為什么會發生?在這里使用 typedef 是絕對必要的嗎?在我的代碼中,我從不使用 typedef 作為結構型別,所以我正在尋找一種方法來避免這種情況,如果可能的話。
uj5u.com熱心網友回復:
在本宣告中
struct {
int a;
double b;
member_struct c;
} outside_struct;
宣告了outside_struct未命名結構型別的物件。沒有struct outside_struct宣告同名的結構。
所以編譯器在這個陣列宣告中發出錯誤
struct outside_struct my_struct_array[4];
因為在此宣告中引入了struct outside_struct未定義的型別說明符。也就是說,在這個宣告中,型別說明符struct outside_struct是一個不完整的型別。
您不能宣告具有不完整元素型別的陣列。
而不是宣告outside_struct 一個未命名結構的物件,你需要宣告一個與標簽名稱相同的結構
struct outside_struct {
int a;
double b;
member_struct c;
};
uj5u.com熱心網友回復:
如果洗掉 typedef,則需要添加一個 struct 標記: struct outside_struct { ... };
uj5u.com熱心網友回復:
Typedef 用于為另一種資料型別創建附加名稱(別名)。
typedef int myInt; //=>equivalent to "int"
myInt index = 0; //=>equivalent to "int index = 0;"
struct 的邏輯是一樣的。
typedef struct myStruct {} myStruct_t; //=> equivalent to "struct myStruct {};"
myStruct_t myStructVariable; //=> equivalent to "struct myStruct myStructVariable;"
語法 = "typedef type newAlias;"
“ myStruct{} ”是一種新型別,包含您想要的所有型別(int、char ...)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364026.html
上一篇:我應該在c中使用有限輸入的fgets或scanf嗎?
下一篇:單個鏈表節點內的多個資料
