[英]How to partially initialize nested element of struct
I'm having trouble initializing an element of a struct which is declared within another struct.我在初始化在另一个结构中声明的结构元素时遇到问题。
My structs look like this:我的结构如下所示:
struct finger
{
// other fields
int pin;
};
struct Glove {
struct finger index;
struct finger middle;
struct finger ring;
struct finger pinkie;
struct finger thumb;
};
//Initializing the array
struct Glove glove = { .index.pin = 20, .middle.pin = 22, .ring.pin = 24, .thumb.pin = 26};
What I'm trying to do is to only initialize the pin variable in the struct finger when declaring a glove struct.我想要做的是在声明手套结构时只初始化结构手指中的pin变量。
However, I get an error message saying:但是,我收到一条错误消息:
expected primary-expression before '.' token
My complete error messages:我的完整错误信息:
Sensor_Glove:40:24: error: expected primary-expression before '.' token
struct Glove glove = { .index.pin = 20, .middle.pin = 22, .ring.pin = 24, .thumb.pin = 26};
^
Sensor_Glove:40:41: error: expected primary-expression before '.' token
struct Glove glove = { .index.pin = 20, .middle.pin = 22, .ring.pin = 24, .thumb.pin = 26};
^
Sensor_Glove:40:59: error: expected primary-expression before '.' token
struct Glove glove = { .index.pin = 20, .middle.pin = 22, .ring.pin = 24, .thumb.pin = 26};
^
Sensor_Glove:40:75: error: expected primary-expression before '.' token
struct Glove glove = { .index.pin = 20, .middle.pin = 22, .ring.pin = 24, .thumb.pin = 26};
^
exit status 1
expected primary-expression before '.' token
The syntax you have used is not valid for initialization of nested struct
s.您使用的语法对嵌套
struct
的初始化无效。 See here -> Nested initialization section - for valid syntax.请参阅 此处-> 嵌套初始化部分 - 了解有效语法。
The following are valid alternatives for what you are trying to achieve.以下是您要实现的目标的有效替代方案。
Using designators ...使用指示符...
struct Glove glove = {
.index = {
.pin = 20
},
.middle = {
.pin = 22
},
.ring = {
.pin = 24
},
.thumb = {
.pin = 26
},
};
Relying on the declaration order of the struct elements ...依赖结构元素的声明顺序......
struct Glove glove3 = {
{20}, // index - pin
{22}, // middle - pin
{24}, // ring - pin
{0}, // pinkie - pin
{26}, // thumb - pin
};
Using designators for outer elements, declaration order for inner ...使用外部元素的指示符,内部元素的声明顺序......
struct Glove glove2 = {
.index = {20}, // pin = 20
.middle = {22}, // pin = 22
.ring = {24}, // pin = 24
.thumb = {26}, // pin = 26
};
Being inconsistent ...不一致...
struct Glove glove4 = {
.index = {20}, // index.pin = 20
{22}, // middle.pin = 22
// Since we are using designators we can change the order
.thumb = {26}, // thumb.pin = 26
.pinkie = {.pin = 24}, // pinkie.pin = 24
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.