gpt4 book ai didi

arrays - 如何部分初始化结构的嵌套元素

转载 作者:太空宇宙 更新时间:2023-11-04 07:46:18 25 4
gpt4 key购买 nike

我在初始化在另一个结构中声明的结构的元素时遇到问题。

我的结构是这样的:

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};

我想做的是在声明 glove 结构时仅初始化结构 finger 中的 pin 变量。 p>

但是,我收到一条错误消息:

expected primary-expression before '.' token

我的完整错误信息:

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

最佳答案

您使用的语法对于嵌套的 struct 的初始化无效。参见 here -> 嵌套初始化部分 - 用于有效语法。

以下是您要实现的目标的有效替代方案。

使用指示符...

struct Glove glove = {                                                                                 
.index = {
.pin = 20
},
.middle = {
.pin = 22
},
.ring = {
.pin = 24
},
.thumb = {
.pin = 26
},
};

依赖结构体元素的声明顺序...

struct Glove glove3 = {
{20}, // index - pin
{22}, // middle - pin
{24}, // ring - pin
{0}, // pinkie - pin
{26}, // thumb - pin
};

对外部元素使用指示符,对内部元素使用声明顺序......

struct Glove glove2 = {                                                                                
.index = {20}, // pin = 20
.middle = {22}, // pin = 22
.ring = {24}, // pin = 24
.thumb = {26}, // pin = 26
};

不一致...

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
};

关于arrays - 如何部分初始化结构的嵌套元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56696428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com