Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array of const structs

Tags:

arrays

c

struct

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

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?

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

like image 694
Bob Broadley Avatar asked Mar 30 '26 16:03

Bob Broadley


2 Answers

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).

You could write:

#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 };
like image 120
M.M Avatar answered Apr 02 '26 13:04

M.M


You should describe the error you get. Trying to compile it myself resulted in:

main.cpp:14:33: error: initializer element is not a compile-time constant
const ARPINFO arpInfoArray[2] = {majorArp,minorArp}; // ERROR HERE
                                ^~~~~~~~~~~~~~~~~~~

To which the solution is:

const ARPINFO arpInfoArray[2] = {
  {3,"Major Arpeggio",{0.0,JUST_MAJ_3,JUST_PERF_5}},
  {3,"Minor Arpeggio",{0.0,JUST_MIN_3,JUST_PERF_5}}
};
like image 26
bames53 Avatar answered Apr 02 '26 12:04

bames53