Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An array of structures in C

For the life of me I can't figure out the proper syntax for creating an array of structures in C. I tried this:

struct foo {
    int x;
    int y;
} foo[][] = {

    {
        { 1, 2 },
        { 4, 5 },
        { -1, -1 }
    },

    {
        { 55, 44 }
        { 100, 200 },
    }
};

So for example foo[1][0].x == 100, foo[0][1].y == 5, etc. But GCC spits out a lot of errors.

If anyone could provide the proper syntax that'd be great.

EDIT: Okay, I tried this:

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

struct foo bar[2][] = {

     {
      { "A", 1 },
      { "B", 2 },
      { NULL, -1 },
     },

     {
      { "AA", 11 },
      { "BB", 22 },
      { NULL, -1 },
     },

     {
      { "ZZ", 11 },
      { "YY", 22 },
      { NULL, -1 },
     },

     {
      { "XX", 11 },
      { "UU", 22 },
      { NULL, -1 },
     },
};

But GCC gives me "elements of array bar have incomplete type" and "excess elements in array initializer".

like image 542
00010000 Avatar asked Jan 23 '23 04:01

00010000


2 Answers

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.

like image 167
Matthew Flaschen Avatar answered Jan 25 '23 22:01

Matthew Flaschen


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.

like image 25
Eli Courtwright Avatar answered Jan 25 '23 23:01

Eli Courtwright