在C中的struct内部初始化数组

时间:2019-01-13 19:02:04

标签: c compilation

我想初始化一个结构变量数组,而结构本身由字节数组组成

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

2 个答案:

答案 0 :(得分:2)

您错过了{}

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 },
};

答案 1 :(得分:2)

您需要两对斜括号{}

struct my_bytes data[] = {
    { { 0x12, 0x34, 0x56, 0x78 } },
    { { 0x13, 0x35, 0x57, 0x79 } },
    { { 0x14, 0x36, 0x58, 0x7a } },
};

外部用于结构,内部用于数组。