Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare array based on size of another array

I have an array of color codes, the size of which is known at compile time. I want to declare another array of the same size. But the code below throws an error.

I can, of course, declare the size as a global constant and then use that in the declaration of both arrays. But I don't want to keep adjusting the size constant when I add new colors. Is there a way to do this? (The variables are global.)

static const char *colors[] = {"#0000ff",
                                "#00ff00",
                                "#ff0000",
                                "#ffff00",
                                "#ff00ff",
                                "#00ffff",
                                "#ffffff",
                                "#000000",
                                "#ff8040",
                                "#c0c0c0",
                                "#808080",
                                "#804000"};

static const int NUM_COLORS = sizeof(colors) / sizeof(colors[0]);
static ColorButtons color_buttons[NUM_COLORS];
like image 766
Mike Avatar asked Oct 18 '25 01:10

Mike


1 Answers

In C opposite to C++ variables with the qualifier const are not part of compile-time constant expressions. And you may not define a variable length array with static storage duration either in a file scope or in a block scope with storage class specifier static.

Instead you could write for example

static enum { NUM_COLORS = sizeof(colors) / sizeof(colors[0]) };
static ColorButtons color_buttons[NUM_COLORS];

Another approach is the following

static ColorButtons color_buttons[sizeof(colors) / sizeof(colors[0])];
static const size_t NUM_COLORS = sizeof(colors) / sizeof(colors[0]);

though there are two times used the expression sizeof(colors) / sizeof(colors[0]).

Or if your compiler supports C23 then

constexpr size_t NUM_COLORS = sizeof(colors) / sizeof(colors[0]);
static ColorButtons color_buttons[NUM_COLORS];
like image 119
Vlad from Moscow Avatar answered Oct 20 '25 16:10

Vlad from Moscow