C 在复合文本中分配匿名联合是否可能(合法)?
我有一个结构:C 在复合文本中分配匿名联合是否可能(合法)?,c,c99,unions,compound-literals,C,C99,Unions,Compound Literals,我有一个结构: typedef struct _n { int type; union { char *s; int i; }; } n; 当我尝试分配复合文字时,如: node n1 = {1, 0}; node n2 = {2, "test"}; gcc给了我一些警告,例如: warning: initialization makes pointer from integer without a cast warning: init
typedef struct _n
{
int type;
union {
char *s;
int i;
};
} n;
当我尝试分配复合文字时,如:
node n1 = {1, 0};
node n2 = {2, "test"};
gcc给了我一些警告,例如:
warning: initialization makes pointer from integer without a cast
warning: initialization from incompatible pointer type
很明显,编译器不确定我是否只是给一个可能不明确的类型赋值。但是,即使我尝试更精确地指定:
node n0 = {type: 1, i: 4};
我得到:
error: unknown field ‘i’ specified in initializer
我已经读到,如果我把
(union)
放在I:
之前,那么它可能会工作。然而,我更喜欢有一个匿名的联盟。有办法做到这一点吗?匿名联合不是标准的C——它们是编译器的扩展。我强烈建议给工会起个名字。如果坚持使用匿名联合,则只能为其第一个元素提供初始值设定项:
node n0 = {1, 0}; // initializes `s' to 0
当使用-Wall-Wextra-pedantic
编译时,gcc给了我一个警告“初始化器周围缺少大括号”,这是一个有效的警告。初始值设定项的实际指定方式如下:
node n0 = {1, {0}}; // initializes `s' to 0
现在,这只给出了一个警告:“ISO C不支持未命名的结构/联合”
如果您为该联盟命名,则可以使用名为“指定初始值设定项”的C99功能来初始化该联盟的特定成员:
typedef struct
{
int type;
union {
char *s;
int i;
} value;
} node;
node n0 = {1, { .s = "string" }};
node n1 = {2, { .i = 123 }};
你需要工会有一个名字;否则,编译器将抱怨其中指定的初始值设定项
您试图使用的
节点n0={type:1,i:4}
语法无效;看起来您试图使用指定的初始值设定项。我第一次看到它时很惊讶,但对GCC来说,这实际上是合法的(尽管不推荐使用)指定初始值设定项语法。我想这是从阅读一些内核模块代码中获得的(我猜不推荐使用)初始值设定项语法。'FOP的结构通常是这样写的。我现在就换成C99路。匿名工会太糟糕了,我不知道它们不是标准的,谢谢你帮我澄清。你确定有一个代码>在123
或“字符串”
之后?它不能为我编译。它不用它就可以编译。@chmike:哎呀,不知道我11年前为什么这么做你是对的,里面不应该有分号。现在修好了。