如何创建一个const结构数组 [英] How to create an array of const structs

查看:362
本文介绍了如何创建一个const结构数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够轻松创建具有特定信息的const结构,因此决定一次一行地"声明和初始化它们,因此我可以根据需要简单地添加新的const结构.这可以正常工作,但是如何创建某种数组来访问这些const结构中的每一个?我尝试了以下操作,但不起作用.

I want to be able to create const structs with specific info easily, so have decided to declare and initialise them "one-line-at-a-time", so I can simply add new const structs as I need them. This works fine, but how can I create some kind of array to access each of these const structs? I tried the following, but it doesn't work.

typedef struct
{
    int numOfNotes;
    char *arpName;
    double freqRatios[12];
} ARPINFO;

const ARPINFO majorArp = {3,"Major Arpeggio",{0.0,JUST_MAJ_3,JUST_PERF_5}};
const ARPINFO minorArp = {3,"Minor Arpeggio",{0.0,JUST_MIN_3,JUST_PERF_5}};

const ARPINFO arpInfoArray[2] = {majorArp,minorArp}; // ERROR HERE

如果我可以使用这种方式来组织结构,则每次创建新的const结构时,只需更改数组的大小并将新的const结构添加到数组中即可.

If I can use this way of organising my structs, I'll only have to change the size of the array and add the new const struct to the array, each time I create a new const struct.

还是我在这里偏离了轨道?枚举或宏可以帮助我吗?

Or am I way off track here? Would enums or MACROS help me out?

freqRatios是用宏定义的,我知道最初的0.0可能是多余的...

The freqRatios are defined with macros and I understand that the initial 0.0 is likely to be redundant...

推荐答案

具有静态存储持续时间的变量必须在C中具有编译时常量初始化程序.并且另一个变量不算作编译时常量(即使该变量也是如此)是const).

Variables with static storage duration have to have compile-time constant initializers in C. And another variable does not count as a compile-time constant (even if that variable is const).

您可以这样写:

#define MAJOR_ARP {3,"Major Arpeggio",{0.0,JUST_MAJ_3,JUST_PERF_5}}
#define MINOR_ARP {3,"Minor Arpeggio",{0.0,JUST_MIN_3,JUST_PERF_5}}

const ARPINFO majorArp = MAJOR_ARP;
const ARPINFO minorArp = MINOR_ARP;

const ARPINFO arpInfoArray[2] = { MAJOR_ARP, MINOR_ARP };

请注意,这具有您的数据的两个副本.如果可以保留一个数据副本和其他引用该数据的静态变量,则可以执行以下操作:

Note that this has two copies of your data. If you're OK with having one copy of the data and the other static variables referencing it, you could instead do:

const ARPINFO *const arpInfos[2] = { &majorArp, &minorArp };

这篇关于如何创建一个const结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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