5

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?

quinmars
  • 11,175
  • 8
  • 32
  • 41

1 Answers1

5

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.

Robert Gamble
  • 106,424
  • 25
  • 145
  • 137
  • Does that dynamically allocate the memory for the two 'point's? – aib Dec 16 '08 at 01:28
  • @aib: Yes, it creates an array of two literal "point" structures (with static storage duration since it's at file scope) and initializes the "foo" member of "test" to point to them. It is a shortcut that is equivalent to defining an array separately and assigning the "foo" member to point to it. – Robert Gamble Dec 16 '08 at 05:23