2

I'm trying to initialize a nested structure array.

Here is what I am doing:

// init a nested struct
struct L1 {
    struct L2 {
        int i[4];
    } l2[3];
};

L1::L2 l2 = {1,2,3,4};

L1::L2 l2_a[] = { {1,2,3}, {1,2}, {1,2,3,4}};

L1 l1 = {
    {{1,2,3}, {1,2}, {1,2,3,4}}
};

L1 l1_a0 = {};
L1 l1_a1 = {0};

L1 l1_a[] = {
    {{1,2,3}, {1,2}, {1,2,3,4}},
    {{1,2,3}, {1,2}, {1,2,3,4}}
}; // ... error: too many initializers for 'L1'

According to what happens correct above, I would expect the the last line derived (initializing the array of nested struct) to be right, but to my surprise, the compiler doesn't like it.

Can it be done at all? Here's a related post about initializing nested structs. Btw, I'm using g++.

Community
  • 1
  • 1
Jayabalan
  • 21
  • 1
  • 2

2 Answers2

4

Yes you can: another reason to always compile -Wall, since the compiler could give you helpful warnings like:

warning: missing braces around initializer for ‘L1::L2 [3]’

The net result isn't pretty, but you end up wasting fewer trees on your teletype hardcopy of the compiler output:

See it live here: http://ideone.com/YKq3d

struct L1 {
    struct L2 {
        int i[4];
    } l2[3];
};

L1::L2 l2 = { {1,2,3,4} };

L1::L2 l2_a[] = { {{1,2,3}}, {{1,2}}, {{1,2,3,4}}};

L1 l1 = {
    {{{1,2,3}}, {{1,2}}, {{1,2,3,4}}}
};

L1 l1_a0 =  {};
L1 l1_a1 = {{{{0}}}};

L1 l1_a[] = {
    {{{{1,2,3}}, {{1,2}}, {{1,2,3,4}}}},
    {{{{1,2,3}}, {{1,2}}, {{1,2,3,4}}}} 
}; // ... sweet potatoes!


int main()
{
    return 0;
}
sehe
  • 374,641
  • 47
  • 450
  • 633
0
L1 l1_a[] = {  // l1_a
  { // l1_a[0]
    { // l1_a[0].l2
      { // l1_a[0].l2[0]
        {1,2,3,4} // l1_a[0].l2[0].i
      },
      {
        {1,2,3,4}
      },
      {
        {1,2,3,4}
      }
    }
  },
  {
    {
      {
        {1,2,3,4}
      },
      {
        {1,2,3,4}
      },
      {
        {1,2,3,4}
      }
    }
  },
  {
    {
      {
        {1,2,3,4}
      },
      {
        {1,2,3,4}
      },
      {
        {1,2,3,4}
      }
    }
  },
};
Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132