且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C语言结构数组初始化

更新时间:2022-04-15 23:23:32

虽然没有特别优雅的方式的初始化的在C大数组这个样子,这是可能的。您的的必须做它在运行时,由于一些答案冒领。而你的不要的做,在运行时,假设数组是常量

While there is no particularly elegant way to initialize a big array like this in C, it is possible. You do not have to do it in runtime, as some answers falsely claim. And you don't want to do it in runtime, suppose the array is const?

我做的方式是通过定义一些宏:

The way I do it is by defining a number of macros:

struct ABC {
  int a; 
  int b;
};

#define ABC_INIT_100 ABC_INIT_50 ABC_INIT_50
#define ABC_INIT_50  ABC_INIT_10 ABC_INIT_10 ABC_INIT_10 ABC_INIT_10 ABC_INIT_10
#define ABC_INIT_10  ABC_INIT_2 ABC_INIT_2 ABC_INIT_2 ABC_INIT_2 ABC_INIT_2
#define ABC_INIT_2   ABC_INIT_1 ABC_INIT_1
#define ABC_INIT_1   {10, 20},

int main()
{
  struct ABC xyz[100] =
  {
    ABC_INIT_100
  };
}

注意,像这些宏可以任何方式进行组合,以使任何数量的初始化的。例如:

Note that macros like these can be combined in any way, to make any number of initializations. For example:

#define ABC_INIT_152 ABC_INIT_100 ABC_INIT_50 ABC_INIT_2