The problem is that all static storage duration variables work with initializer lists that need to be compile-time constants, as defined by the language. Another variable, even if declared as const
, is not considered a compile-time constant. In addition, you can't initialize or directly assign an array from another array.
So you can't do this because of limits in the language. Your version with #defines
for the initializer lists is actually a common solution to this. It is a simple solution so it might be the best one.
If you are looking for a way to access the data in different ways, one alternative could be something with unions and C11 anonymous structures:
#include <stdio.h>
#define FOO_INIT 1, 2, 3
#define BAR_INIT 4, 5, 6, 7
#define FOO_SIZE ( sizeof((int[]){ FOO_INIT }) / sizeof(int) )
#define BAR_SIZE ( sizeof((int[]){ BAR_INIT }) / sizeof(int) )
typedef union
{
int array [FOO_SIZE + BAR_SIZE];
struct
{
int foo [FOO_SIZE];
int bar [BAR_SIZE];
};
} foobar_t;
int main (void)
{
static const foobar_t foobar = { .foo = {FOO_INIT}, .bar = {BAR_INIT} };
// print 1 2 3 4 5 6 7
for(size_t i=0; i<FOO_SIZE + BAR_SIZE; i++)
{
printf("%d ", foobar.array[i]);
}
}
Now if you wish to make a hardcopy of the array(s), you can actually just do foobar_t foobar2 = foobar;
. C is quite weird, because while it doesn't allow assignment of arrays, it is perfectly fine with assignment of structures/unions containing arrays. (But that will still not work if foobar2
has static storage duration.)