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

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

问题描述

我有结构

struct ABC {
  int a; 
  int b;
}

和它的数组

struct ABC xyz[100];

我想将其初始化为 a = 10 和 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天全站免登陆