views:

216

answers:

2
+7  A: 

This creates and initializes a two-dimensional array of structures, with each row containing three. Note that you haven't provided an initializer for the array[1][2], which in this case means its contents is undefined.

struct foo {
    const char *x;
    int y;
};

int main()
{
    struct foo array[][3] = {
        {
            { "foo", 2 },
            { "bar", 5 },
            { "baz", -1 },
        },
        {
            { "moo", 44 },
            { "goo", 200 },
        }
    };
    return 0;
}

EDIT: Made x pointer to const string. Try to make your examples close to your real code.

Matthew Flaschen
Thanks. Still can't get it to work on my end though (replace int x with const char *x above, and then change the initialization accordingly from int (eg 55 above) to "foo"... GCC spits out a ton of "excess elements in array initializer" errors).
00010000
There's an extra comma after { 100, 200 }
progrmr
Look at Matthew's `struct foo array[][3]` and at your `struct foo bar[2][]`. Fix that and your edited question should work.
Matt B.
@kk6yb: That's probably okay. Trailing commas are a very widely accepted extension and became canonical in C99.
Matt B.
Actually, trailing commas in initializers are standard C89. It's only enums that previously didn't allow it.
Matthew Flaschen
Sweet, thanks. Got it to work... turns out in array[][3], 3 should be the max number of elements you'll be using (e.g, if you added "blah" after "foo"/"bar"/"baz" you'd have to change 3 to 4).
00010000
It's not actually the maximum, it's the exact width of the row. As I said, the initializer is too short the contents of the extra locations will be undefined (for stack variables).
Matthew Flaschen
+2  A: 

I think the easiest approach would be to split up the struct and array declarations:

struct foo {
    int x;
    int y;
};

int main()
{
    struct foo foo_inst = {1, 2};
    struct foo foo_array[] = {
        {5, 6},
        {7, 11}
    };
    struct foo foo_matrix[][3] = {
        {{5,6}, {7,11}},
        {{1,2}, {3,4}, {5,6}}
    };

    return 0;
}

The problem is that nested array declarations in C (and C++) cannot have arbitrary length for any array except the outermost. In other words, you can't say int[][] arr, and you must instead say int[][5] arr. Similarly, you can't say int[][6][] arr or int [][][7] arr, you would have to say int[][6][7] arr.

Eli Courtwright