Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

too many initializers for array in struct

Tags:

c++

c++11

I have:

struct X {
    int i, j;
};

struct XArray {
    X xs[3];
};

X xs1[3] { {1, 2}, {3, 4}, {5, 6} };
XArray xs2 { {1, 2}, {3, 4}, {5, 6} };

The xs1 initializes fine, initializing xs2 gives compiler error:

error: too many initializers for 'XArray'
 XArray xs2 { {1, 2}, {3, 4}, {5, 6} };
                                     ^

What is wrong? Why can't I initialize?

like image 828
nullptr Avatar asked Dec 07 '22 18:12

nullptr


2 Answers

You need another level of curly-braces:

XArray xs2            { { {1, 2}, {3, 4}, {5, 6} } };
//                    ^ ^ ^
//                    | | |
// For XArray structure | |
//                      | |
//           For xs array |
//                        |
//      For the X structure
like image 113
Some programmer dude Avatar answered Feb 11 '23 23:02

Some programmer dude


The compileŕ assumes that xs is one field, the array will only be resolved when you add another brace like:

XArray xs2 { {{1, 2}, {3, 4}, {5, 6}} };

When you would add another element, e.g.

struct YArray {
    X a; 
    X xs[3];
 }

then it becomes clear that a and xs both need to be put into braces:

YArray y{ 
            {1,2}, // a 
            { {1, 2}, {3, 4}, {5, 6} } // xs 
        };
like image 39
Gert Wollny Avatar answered Feb 12 '23 01:02

Gert Wollny