c结构体数组初始化 [英] c structure array initializing

查看:31
本文介绍了c结构体数组初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有结构

struct ABC {
  int a; 
  int b;
}

并将它的数组作为

struct ABC xyz[100];

我想初始化它 a = 10 and b = 20;对于所有数组元素.

I want to initialize it a = 10 and b = 20; for all array element.

哪种方法更好?

推荐答案

虽然在 C 中没有特别优雅的方法来初始化这样的大数组,但这是可能的.正如一些答案错误地声称的那样,您不必在运行时执行此操作.而你不想在运行时这样做,假设数组是const?

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

这篇关于c结构体数组初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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