2015-10-16 211 views
0

我在Arduino的C上工作。我試圖初始化一個結構(鏈表)內的指針。它是一個數據對象,所以我想一次初始化整個對象,而不是稍後在代碼中使用malloc。C - 初始化結構中的指針

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

你說的意思是什麼「死了」 ? – WhiteViking

+1

你不能像這樣初始化......你試圖初始化一個指針,使其等於一個結構。你可能認爲你可以這樣做,因爲類似的模式適用於C字符串,但它非常專業。您將需要初始化指針以指向具體位置,可能在運行時而不是編譯時。 – mah

回答

1

因爲它是在評論說 - 你需要有一個指針,而是提供結構中的主要問題,一個變體來解決,這可能是:

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