5

I use below way to initialize an array of CandyBar structure, but compiler always says excess elements in struct initializer. I tried putting only one structure initializer in the array definition, it compiled, but the rest 2 elements of the array are null
What should I do?

struct CandyBar{
    string brand;
    float weight;
    int calories;
};

int main(int argc, const char * argv[]) {

        array<CandyBar, 3> ary_cb =
    {
        {"Mocha Munch", 2.3, 350},
        {"Mocha Munch", 2.3, 350},
        {"Mocha Munch", 2.3, 350}
    };
    return 0;
}
Roybot
  • 115
  • 1
  • 3

3 Answers3

5

You are missing a pair of braces around your structures (remember, std::array is a struct containing an array):

    array<CandyBar, 3> ary_cb =
    {
        { 
            {"Mocha Munch", 2.3, 350} ,
            {"Mocha Munch", 2.3, 350} ,
            {"Mocha Munch", 2.3, 350} 
        }
    };
quantdev
  • 23,517
  • 5
  • 55
  • 88
  • `remember, std::array is a struct containing an array` This isn't technically guaranteed, either way the braces can be elided as of C++14 although compilers (gcc at least) have yet to catch up. – user657267 Dec 18 '14 at 04:58
  • 1
    Thanks for answering. but if it's an int array, it could be written as array a = {2, 3, 4}; don't need the pair of braces I missed? – Roybot Dec 18 '14 at 05:13
1

The Reason why the rest 2 elements of the array are null is because you put all the info in the first candybar element and not the other two candybar elements.

Solution:

int main(int argc, const char * argv[]) 
{

    array<CandyBar, 3> ary_cb =
    {
        { //Struct
            {"Mocha Munch", 2.3, 350},
            {"Mocha Munch", 2.3, 350},
            {"Mocha Munch", 2.3, 350}
        }
    };
    return 0;
}

Source - > Link

Snake
  • 113
  • 2
  • 10
0

As well as quantdev's suggestion this also works (in C++11):

array<CandyBar, 3> ary_cb =
{
    "Mocha Munch", 2.3, 350 ,
    "Mocha Munch", 2.3, 350 ,
    "Mocha Munch", 2.3, 350 
};

You have to leave out either all the braces or none, when initializing a nested set of aggregates (i.e. struct / array).

M.M
  • 138,810
  • 21
  • 208
  • 365