【发布时间】:2014-08-09 10:15:41
【问题描述】:
我需要一个嵌入到 struct test 中的匿名结构,以便它的设置如下:
#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-extensions 编译!
#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 } };
但是,如果你这样做,它会给出相同的输出而没有警告。
我希望这可以澄清!
【问题讨论】:
-
你不能使用指针强制转换、联合或继承吗?你的问题不是很清楚...
-
我已经更新了我的问题,希望现在更清楚了。
-
而不是
return 0;表示成功。 -
好的;我已经更改了返回值,即使它不相关。
-
@CHRIS 我不明白。如果您使用
1, 2, 3, 4更改零,您提供的第一个代码的输出是什么?它仍然应该是零。如果那是你已经追求的,那很好。但是,如果您希望为x设置一个初始值,那么您有很多解决方案,其中之一是... = {{set_of_values_for_name}, {value_for_x, value_for_y}};。