[英]Why can't I initialize an array within a nested structure?
I want to create a new structure that is the combination of two identical structures. 我想创建一个新结构,它是两个相同结构的组合。 Each of these sub structures includes one scalar double and a three dimensional array. 这些子结构中的每一个包括一个标量双和三维阵列。 However, when I try to initialize the structure I am getting errors when attempting to give the array its values. 但是,当我尝试初始化结构时,我在尝试给数组赋值时遇到错误。
I don't have compilation errors, but when I try to look into the values of the array within the nested structure, I see very completely wrong insane numbers. 我没有编译错误,但是当我尝试在嵌套结构中查看数组的值时,我看到非常完全错误的疯狂数字。
Do you know what I am doing wrong here? 你知道我在做错了什么吗?
typedef struct quackStruct {
double s;
double v[3];
} quackStruct;
typedef struct dualquackStruct {
quackStruct q1;
quackStruct q2;
} dualquackStruct;
int main() {
quackStruct duck1 = { .s = 0.0, .v = { 0.5,4.0,2.1 } };
quackStruct duck2 = { .s = 0.85, .v = { 20.0, 10.0, -5.0 } };
/* I tried this... but it didn't work
dualquackStruct ducks = { duck1, duck2 }; */
/* this didn't work either */
dualquackStruct ducks = { .q1.s = 0.0, .q1.v = { 0.5, 4.0, 2.1 },
.q2.s = 0.85, .q2.v = { 20.0, 10.0, -5.0 } };
printf("%f\n", ducks.q1.s);
printf("%f\n", ducks.q1.v[0]);
printf("%f\n", ducks.q1.v[1]);
printf("%f\n", ducks.q1.v[2]);
printf("%f\n", ducks.q2.s);
printf("%f\n", ducks.q2.v[0]);
printf("%f\n", ducks.q2.v[1]);
printf("%f\n", ducks.q2.v[2]);
return 0;
}
Your first line does compile. 你的第一行编译。 But - you can't define the same variable twice... 但是 - 你不能两次定义相同的变量......
In your second line, you need to perform nested-initialization of the q1 and the q2 structure within braces, not to go two-levels down with .firstlevelfield.secondlevelfield.: 在你的第二行中,你需要在大括号内执行q1和q2结构的嵌套初始化,而不是使用.firstlevelfield.secondlevelfield进行两级降低:
dualquackStruct ducks = { .q1 = { .s = 0.0, .v = { 0.5, 4.0, 2.1} },
.q2 = { .s = 0.85, .v = {20.0, 10.0, -5.0} } };
See both lines (after the correction) compiling (GodBoot). 看两行(校正后)编译 (GodBoot)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.