![](/img/trans.png)
[英]How to initialise an array of pointers to NULL that's inside a struct, and the struct is within an array of other structs
[英]Initialise array inside struct in C
我想初始化一個結構變量數組,而結構本身由字節數組組成
struct my_bytes {
u8 byte[128];
};
struct my_bytes data[] = {
{ 0x12, 0x34, 0x56, 0x78 },
{ 0x13, 0x35, 0x57, 0x79 },
{ 0x14, 0x36, 0x58, 0x7a },
};
編譯在本機gcc 4.8.5中可以,但是在其他編譯器/環境中則出錯。還有另一種初始化數據的方法嗎?
錯誤信息
it_sram.c:200:3: error: missing braces around initializer [-Werror=missing-braces]
it_sram.c:200:3: error: (near initialization for 'data[0].byte') [-Werror=missing-braces]
it_sram.c:199:18: error: unused variable 'data' [-Werror=unused-variable]
it_sram.c: At top level:
cc1: error: unrecognized command line option "-Wno-misleading-indentation" [-Werror]
cc1: all warnings being treated as errors
您錯過了{}級
struct my_bytes data[] = {
{{ 0x12, 0x34, 0x56, 0x78 } },
{{ 0x13, 0x35, 0x57, 0x79 } },
{{ 0x14, 0x36, 0x58, 0x7a } },
};
如果我將結構更改為:
struct my_bytes {
u8 byte[128];
int a;
};
您需要這樣的東西:
struct my_bytes data[] = {
{{ 0x12, 0x34, 0x56, 0x78 }, 1 },
{{ 0x13, 0x35, 0x57, 0x79 }, 2 },
{{ 0x14, 0x36, 0x58, 0x7a }, 3 },
};
您需要兩對斜括號{}
:
struct my_bytes data[] = {
{ { 0x12, 0x34, 0x56, 0x78 } },
{ { 0x13, 0x35, 0x57, 0x79 } },
{ { 0x14, 0x36, 0x58, 0x7a } },
};
外部用於結構,內部用於數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.