我需要嵌入到struct测试中的匿名结构,这样就可以像下面这样设置它:
#include <stdio.h>
struct test {
char name[20];
struct {
int x;
int y;
};
};
int main(void) {
struct test srs = { "1234567890123456789", 0, 0 };
printf("%d\n", srs.x); // I can access x property without having to go to go within another struct
return 0;
}这样我就可以访问x和y属性,而不必进入另一个结构中。
但是,我希望能够使用在其他地方声明的结构定义,如下所示:
struct position {
int x;
int y;
}我无法编辑上述结构!
因此,例如,一些伪代码可能是:
#include <stdio.h>
struct position {
int x;
int y;
};
struct test {
char name[20];
struct position;
};
int main(void) {
struct test srs = { "1234567890123456789", 0, 0 };
printf("%d\n", srs.x); // I can access x property without having to go to go within another struct
return 0;
}然而,这意味着:
warning: declaration does not declare anything
In function 'main':
error: 'struct test' has no member named 'x'更新:一些评论者想知道如何初始化这样的结构,所以我为您编写了一个简单的程序供您试用,确保按照答案使用-fms-扩展进行编译!
#include <stdio.h>
struct position {
int x;
int y;
};
struct test {
char name[20];
struct position;
};
int main(void) {
struct test srs = { "1234567890123456789", 1, 2 };
printf("%d\n", srs.x);
return 0;
}输出为1,这是您所期望的。
不需要:
struct test srs = { "1234567890123456789", { 1, 2 } };但是,如果您这样做,它将提供相同的输出,没有警告。
我希望这能澄清!
发布于 2014-08-09 10:37:22
按照c11标准,在gcc中使用匿名结构是可能的。使用-fms-extensions编译器选项将允许您所需的匿名结构特性。
相关文档摘录:
除非使用-fms-扩展名,否则未命名的字段必须是没有标记的结构或联合定义(例如,‘struct{ int a;};’‘)。如果使用-fms-扩展,则该字段还可以是一个带有标记的定义,例如“structure { int a;}”、对先前定义的结构或联合(如‘struct foo;’)的引用,或者是对先前定义的结构或联合类型的type名称的引用。
有关更多信息,请参阅:this page。
发布于 2014-08-09 10:20:58
#define position {int x; int y;}
struct test {
char name[20];
struct position;
};扩大到:
struct test {
char name[20];
struct {int x; int y;};
};https://stackoverflow.com/questions/25217505
复制相似问题