![](/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.