C - 初始化结构中的指针

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

最佳答案

正如评论中所说 - 您需要指针但提供结构的主要问题,解决此问题的一种变体可能是:

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

关于C - 初始化结构中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33178470/

相关文章:

c - 为什么 scanf 不允许更多输入?

c - 指针数组 *(*(string+i)+j)。 (这可能吗?)

c - 这两种内存分配方式有什么区别呢?

c - 未知类型名称 C 与 C++

c - 使用结构时 fscanf 的问题

c - 警告 : format ‘%s’ expects argument of type ‘char *’ , 但参数 2 的类型为 ‘char (*)[30]’ [-Wformat=]

c - 非二进制补码平台上 char 中的 ASCII 代码表示

c - 如果文件不存在,程序在 C 中失败

c - Socket 客户端发送 1 个长字符串而不是 3 个字符串

c - 在 C 中对字符串/结构数组进行排序