Initializing only one member in a C struct for an

2019-07-24 03:53发布

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

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? I know in C++, this is accomplished by providing a constructor for the struct initializing b only.

1条回答
干净又极端
2楼-- · 2019-07-24 04:02

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

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

It works with clang >= 5 too.

查看更多
登录 后发表回答