简体   繁体   English

初始化C结构中的一个成员以获取结构元素数组

[英]Initializing only one member in a C struct for an array of struct elements

I have the following code with an intention to initialize member b. 我有以下代码旨在初始化成员b。 This should happen for all the MAX_SIZE structs. 所有MAX_SIZE结构都应该发生这种情况。

enum { MAX_SIZE = 10 };

struct some
{
    int a, b;
}
many[MAX_SIZE] = { {.b = 5} };

int main() 
{
    int i;

    for (i = 0; i < MAX_SIZE; i++)
    {
        printf("%d, %d\n", many[i].a, many[i].b);
    }
}

I need the output to look like: 我需要输出看起来像:

0, 5
0, 5
0, 5
... (10 times)

But, the actual output is: 但是,实际输出为:

0, 5
0, 0
0, 0
... (10 times)

How to get the required output without requiring an explicit for loop for assigning the values? 如何在不需要显式for循环来分配值的情况下获得所需的输出? I know in C++, this is accomplished by providing a constructor for the struct initializing b only. 我知道在C ++中,这是通过仅为初始化b的结构提供构造函数来实现的。

It's not C Standard, but with this gcc extension you can do this : 它不是C Standard,但是通过gcc扩展,您可以执行以下操作:

struct some many[10] = { [0 ... 9].b = 5 };

It works with clang >= 5 too. 它也适用于clang >= 5

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

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