C - 初始化结构中的指针

时间:2015-10-16 19:45:46

标签: c pointers struct arduino

我正在使用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
};

1 个答案:

答案 0 :(得分: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};