我想初始化這個結構:如何在C中的聯合中使用指針?
typedef struct
{
int num;
union
{
const char** ppStrList;
const char* pStr;
};
union
{
int num1;
int num2;
};
} tMyStruct;
如果我嘗試當我宣佈變量,我得到一個錯誤初始化這個結構:例如,
const char *gpStr = "str";
const char *gpStrList[2] =
{
{"str1"},
{"str2"}
};
tMyStruct myStruct[2] =
{
{0,{gpStrList},{3}},
{1,{gpStr},{4}}
};
變量gpStr
不容被用來初始化結構
但它可以在函數中沒有問題初始化:
int main(int argc, char *argv[])
{
myStruct[0].num = 0;
myStruct[0].ppStrList = gpStrList;
myStruct[0].num1 = 3;
myStruct[1].num = 0;
myStruct[1].pStr = gpStr;
myStruct[1].num2 = 3;
}
爲什麼結構不能初始化何時宣佈?
我認爲工會有一個特殊的行爲,因爲如果我不使用聯合問題不存在。例如:
typedef struct
{
int num;
union /* Union to contain ppStrList and pStr pointers */
{
const char** ppStrList;
const char* pStr;
};
union
{
int num1;
int num2;
};
} tMyStruct1;
typedef struct
{
int num;
/* I don´t use an union */
const char** ppStrList;
const char* pStr;
union
{
int num1;
int num2;
};
} tMyStruct2;
const char gStr[] = "str";
const char *gpStrList[2] =
{
{"str1"},
{"str2"}
};
tMyStruct1 myStruct1[2] = /* Structure with union inside */
{
{0,{gpStrList},{3}},
{1,{gStr},{4}} /* <--- Error here if I use gStr address with union */
};
tMyStruct2 myStruct2[2] = /* Structure without union inside */
{
{0,gpStrList,NULL,{3}},
{1,NULL,gStr,{4}} /* <--- No poblem here if I use gStr address */
};
我敢說,這: '工會 { INT NUM1; int num2; };' 證明你根本不應該使用聯合。 – Dariusz