简体   繁体   中英

Initialise array inside struct in C

I wants to initialise an array of struct variable, while the struct itself consists of array of bytes

struct my_bytes {
    u8 byte[128];
};

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

Compile is fine in native gcc 4.8.5 but error in other compiler/environment Is there another way to initialise data?

Error message

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

you missed a level of {}

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

to have that more visible if I change the struct to be :

struct my_bytes {
  u8 byte[128];
  int a;
};

you need something like that :

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

You need two pairs of curcly braces {} :

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

The outer is for the structure, the inner for the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM