简体   繁体   English

如何初始化结构类型的数组?

[英]how do I initialize an struct type of array?

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. 我知道有关于此警告的gcc错误。 Or am I doing something wrong? 或者我做错了什么?

You need to use struct_array structArray1 = {{{0}}}; 您需要使用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. 代码是正确的,但你的GCC是错误的,如其他答案中所述。

Your code is completely correct. 您的代码完全正确。 And you're right that GCC has a bug, too - it's described here . 你也是对的,GCC也有一个错误 - 这里有描述

You have a couple of choices: 你有几个选择:

  1. Disable -Wmissing-braces for now. -Wmissing-braces禁用-Wmissing-braces

  2. Use empty initalizer braces (GCC extension): 使用空的initalizer支架(GCC扩展):

     struct_array structArray1 = {}; 
  3. Initialize one complete object. 初始化一个完整的对象。 For a three-element struct_t , for example: 对于三元素struct_t ,例如:

     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: 假设结构类型与上面的#3相同,并且是2x2数组:

     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. 修复GCC中的错误。

Try: 尝试:

int main(){
    struct_t structArray[ROWS][COLS];
    memset(structArray, 0, sizeof(structArray));
}

(memset fills it with zeroes) (memset用零填充)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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