Nested structures/arrays initialization
Asked Answered
E

1

6

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?

Echoism answered 12/12, 2008 at 13:16 Comment(0)
R
6

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.

Rawley answered 12/12, 2008 at 13:23 Comment(2)
Does that dynamically allocate the memory for the two 'point's?Acrilan
@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.Rawley

© 2022 - 2024 — McMap. All rights reserved.