我想初始化这个结构:
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 */
};