[英]C - Initialize a pointer in a struct
我在Arduino上使用C語言工作。 我正在嘗試初始化結構(鏈接列表)中的指針。 它本來是一個數據對象,所以我想立即初始化整個對象,而不是稍后在代碼中使用malloc。
const int PINS_LEN = 20;
struct Command {
float toBrightness; //Percent
float overTime; //Seconds
};
struct CommandNode {
struct Command command;
struct CommandNode *next;
};
struct Sequence {
struct CommandNode commands;
float startTime;
float staggerTime;
int pins[PINS_LEN];
};
struct SequenceNode { //Pattern
struct Sequence sequence;
struct SequenceNode *next;
};
struct SequenceNode pattern = {
.sequence = {
.commands = {
.command = {
.toBrightness = 100,
.overTime = 1.0
},
//-=-=-=THIS IS WHERE IT DIES=-=-=-
.next = {
.command = {
.toBrightness = 50,
.overTime = 0.5
},
.next = NULL
},
//-=-=-=-=-=-=-=-=-=-=
},
.startTime = 0.0,
.staggerTime = 1.0,
.pins = {0, 1, 2, 3, 4, 5}
},
.next = NULL
};
正如評論中所說的那樣-主要問題是您需要指針,但要提供結構,可以解決此問題的一種變體可能是:
struct CommandNode next = {.command = {.toBrightness = 50, .overTime = 0.5}, .next = NULL};
struct SequenceNode pattern = {.sequence = {
.commands = {
.command = {.toBrightness = 100, .overTime = 1.0},
.next = &next},
.startTime = 0.0,
.staggerTime = 1.0,
.pins = {0, 1, 2, 3, 4, 5}
},
.next = NULL};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.