初始化C结构中的一个成员以获取结构元素的数组 [英] Initializing only one member in a C struct for an array of struct elements

查看:57
本文介绍了初始化C结构中的一个成员以获取结构元素的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码旨在初始化成员b.所有MAX_SIZE结构都应该发生这种情况.

I have the following code with an intention to initialize member b. This should happen for all the MAX_SIZE structs.

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

我需要输出看起来像:

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

但是,实际输出是:

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

如何在不需要显式的for循环来分配值的情况下获得所需的输出?我知道在C ++中,这是通过仅为初始化b的结构提供构造函数来实现的.

How to get the required output without requiring an explicit for loop for assigning the values? I know in C++, this is accomplished by providing a constructor for the struct initializing b only.

推荐答案

它不是C标准,但是带有 gcc扩展,您可以这样做:

It's not C Standard, but with this gcc extension you can do this :

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

它也可以与 clang >= 5 一起使用.

It works with clang >= 5 too.

这篇关于初始化C结构中的一个成员以获取结构元素的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆