Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I initialize an struct type of array?

Tags:

c

typedef struct_t struct_array[ROWS][COLS];

int main()
{
    struct_array structArray1 = {0};

}

I got an error saying there is a missing braces around the initializer. I know there is a bug of gcc regarding this warning. Or am I doing something wrong?

like image 635
user1701840 Avatar asked Sep 10 '26 21:09

user1701840


2 Answers

You need to use struct_array structArray1 = {{{0}}};, the first one for the 1st dimension of the array, the 2nd one for the 2nd dimension and the third for the struct initialization. The code is right, but your GCC is buggy as stated in other answers.

like image 170
rems4e Avatar answered Sep 13 '26 14:09

rems4e


Your code is completely correct. And you're right that GCC has a bug, too - it's described here.

You have a couple of choices:

  1. Disable -Wmissing-braces for now.

  2. Use empty initalizer braces (GCC extension):

    struct_array structArray1 = {};
    
  3. Initialize one complete object. For a three-element struct_t, for example:

    struct_array structArray1 = { { { 0, 0, 0 } } };
    
  4. Specify all of the necessary braces and zeroes. Assuming the same structure type as in #3 above, and a 2x2 array:

    struct_array structArray1 = { { { 0, 0, 0 }, { 0, 0, 0 },
                                    { 0, 0, 0 }, { 0, 0, 0 } },
                                  { { 0, 0, 0 }, { 0, 0, 0 },
                                    { 0, 0, 0 }, { 0, 0, 0 } } };
    
  5. Use a different compiler. clang, maybe?

  6. Fix the bug in GCC.

like image 36
Carl Norum Avatar answered Sep 13 '26 16:09

Carl Norum