gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:20:50 25 4
gpt4 key购买 nike

编译器错误“错误:数组必须用大括号括起来的初始化器初始化”让我很困惑。这个问题的其他例子似乎都与此无关。我有大约 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"}
};

最佳答案

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

这里,addrDeviceAddress 类型,它只是一个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"},
...
};

但是,通过这种方式,结构只是指向一个外部数组,这可能是不可取的。

关于在 C 中初始化结构数组的编译器错误(数组必须用大括号括起来的初始化器初始化),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35400245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com