![](/img/trans.png)
[英]C error: "Array must be initialized with a brace enclosed initializer"
[英]Compiler error initializing array of structs in C (array must be initialized with a brace-enclosed initializer)
我被編譯器錯誤“錯誤:數組必須用大括號括起來的初始化程序初始化”所困擾。 此問題的其他示例似乎都與此無關。 我已經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"}
};
在這里, 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"},
...
};
但是,以這種方式,該結構僅指向一個外部數組,這可能是不希望的。
如果您使用“ Probe0x”作為幫手,如@MM所要求的那樣使思考更清晰,則可以將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"}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.