c structure array initializing

前端 未结 4 584
鱼传尺愫
鱼传尺愫 2020-11-27 23:02

I have structure

struct ABC {
  int a; 
  int b;
}

and array of it as

struct ABC xyz[100];

I want to in

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 23:42

    With GCC you can use its extended syntax and do:

    struct ABC xyz[100] = { [0 ... 99].a = 10, [0 ... 99].b = 20 };
    

    For a portable solution I'd probably initialize one instance, and use a loop to copy that instance to the rest:

    struct ABC xyz[100] = { [0].a = 10, [0].b = 20 };
    
    for(size_t i = 1; i < sizeof xyz / sizeof *xyz; ++i)
      xyz[i] = xyz[0];
    

    This is somewhat cleaner to me than having the actual values in the loop. It can be said to express the desired outcome at a slightly higher level.

    The above syntax ([0].a and [0].b) is not an extension, it's typical C99.

提交回复
热议问题