编译器错误初始化C中的结构数组(数组必须用括号括起的初始化程序初始化)

时间:2016-02-15 01:34:14

标签: c arrays

我被编译器错误"错误所困扰:数组必须使用括号括起的初始化程序"进行初始化。这个问题的其他例子似乎与此无关。在14年左右的时间里,我还没有触及过C,所以我认为“生锈”这个词并没有触及过它。有点慷慨。我确定我错过了一些愚蠢的事情。

typedef uint8_t DeviceAddress[8];
DeviceAddress Probe01 = { 0x28, 0xFF, 0x87, 0x5A, 0x91, 0x15, 0x04, 0xE0 }; 
DeviceAddress Probe02 = { 0x28, 0xFF, 0x97, 0x5E, 0x91, 0x15, 0x04, 0x92 };
DeviceAddress Probe03 = { 0x28, 0xFF, 0xCD, 0x81, 0x91, 0x15, 0x01, 0x1E };
DeviceAddress Probe04 = { 0x28, 0xFF, 0xA6, 0x69, 0x91, 0x15, 0x04, 0x15 };
DeviceAddress Probe05 = { 0x28, 0xFF, 0xD8, 0x7E, 0x91, 0x15, 0x04, 0x64 };

struct DeviceInfo {
  DeviceAddress addr;
  const char * name;
};

struct DeviceInfo devices[5] = {
  {.addr = Probe01, .name = "Pump1"},
  {.addr = Probe02, .name = "Pump2"},
  {.addr = Probe03, .name = "Pump3"},
  {.addr = Probe04, .name = "Pump4"},
  {.addr = Probe05, .name = "Pump5"}
};

2 个答案:

答案 0 :(得分:3)

struct DeviceInfo devices[5] = {
  {.addr = Probe01, .name = "Pump1"},
  {.addr = Probe02, .name = "Pump2"},
  {.addr = Probe03, .name = "Pump3"},
  {.addr = Probe04, .name = "Pump4"},
  {.addr = Probe05, .name = "Pump5"}
};

此处,addr的类型为DeviceAddress,只是uint8_t数组。您无法在C中分配数组,因此编译器会告诉您将Probe1分配到字段addr中无效;那里需要它自己的括号封闭的数组初始化器。

你有几个选择。您可以完全摆脱Probe01Probe02等,只需按照编译器的建议初始化数组:

struct DeviceInfo devices[5] = {
  {.addr = { 0x28, 0xFF, 0x87, 0x5A, 0x91, 0x15, 0x04, 0xE0 }, .name = "Pump1" },
  ...
};

另一个选项,有点迂回,有两个typedef:

typedef uint8_t DeviceAddress[8];
typedef uint8_t * DeviceAddress_P;

struct DeviceInfo {
  DeviceAddress_P addr;
  const char * name;
};

在结构中使用指针类型,将其初始化为指向您创建的数组的第一个元素:

DeviceAddress Probe01 = { 0x28, 0xFF, 0x87, 0x5A, 0x91, 0x15, 0x04, 0xE0 };

struct DeviceInfo devices[5] = {
  {.addr = Probe01, .name = "Pump1"},
  ...
};

但是,这样,struct只指向一个外部数组,这可能是不可取的。

答案 1 :(得分:1)

如果您使用“Probe0x”作为助手来使@M.M的问题更清晰,您可以将Struct DeviceInfo类型的数组设备初始化为休闲:

struct DeviceInfo devices[5] = {
  {{ 0x28, 0xFF, 0x87, 0x5A, 0x91, 0x15, 0x04, 0xE0 }, "Pump1"},
  {{ 0x28, 0xFF, 0x97, 0x5E, 0x91, 0x15, 0x04, 0x92 }, "Pump2"},
  {{ 0x28, 0xFF, 0xCD, 0x81, 0x91, 0x15, 0x01, 0x1E }, "Pump3"},
  {{ 0x28, 0xFF, 0xA6, 0x69, 0x91, 0x15, 0x04, 0x15 }, "Pump4"},
  {{ 0x28, 0xFF, 0xD8, 0x7E, 0x91, 0x15, 0x04, 0x64 }, "Pump5"}
};