C语言结构数组初始化 [英] c structure array initializing

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

问题描述

我有结构

struct ABC {
  int a; 
  int b;
}

和它的数组

struct ABC xyz[100];

我要初始化一个= 10和b = 20;对于所有的数组元素。

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

这是更好的办法吗?

推荐答案

虽然没有特别优雅的方式的初始化的在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

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

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