Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested structures/arrays initialization

Tags:

I have a structure that contains an arrays of another structure, it looks something like this:


typedef struct bla Bla;
typedef struct point Point;

struct point
{
    int x, y;
};

struct bla
{
    int another_var;
    Point *foo;
};

I now want to initialize them in the global scope. They are intended as description of a module. I tried to do that with c99 compound literals, but the compiler (gcc) didn't like it:


Bla test =
{
    0, (Point[]) {(Point){1, 2}, (Point){3, 4}}
};

I get the following errors:

error: initializer element is not constant
error: (near initialization for 'test')

Since I don't need to modify it I can put as many "const" in it as necessary. Is there a way to compile it?

like image 372
quinmars Avatar asked Dec 12 '08 13:12

quinmars


1 Answers

You don't need a compound literal for each element, just create a single compound literal array:

Bla test =
{
    0, (Point[]) {{1, 2}, {3, 4}}
};

Make sure you compile with -std=c99.

like image 118
Robert Gamble Avatar answered Oct 02 '22 14:10

Robert Gamble