我被编译器错误"错误所困扰:数组必须使用括号括起的初始化程序"进行初始化。这个问题的其他例子似乎与此无关。在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"}
};
答案 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
中无效;那里需要它自己的括号封闭的数组初始化器。
你有几个选择。您可以完全摆脱Probe01
,Probe02
等,只需按照编译器的建议初始化数组:
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"}
};