Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should I do to initialize an array of a structure [duplicate]

Tags:

c++

arrays

c++11

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;
}
like image 703
Roybot Avatar asked Dec 18 '14 04:12

Roybot


People also ask

How do you initialize an array of structures?

If you have multiple fields in your struct (for example, an int age ), you can initialize all of them at once using the following: my_data data[] = { [3]. name = "Mike", [2]. age = 40, [1].

What is the correct way to initialize an array?

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.

What are 2 ways to initialize an array?

There are two ways you can declare and initialize an array in Java. The first is with the new keyword, where you have to initialize the values one by one. The second is by putting the values in curly braces.

How do you initialize an array with the same element?

int arr[10] = {5}; In the above example, only the first element will be initialized to 5. All others are initialized to 0. A for loop can be used to initialize an array with one default value that is not zero.


2 Answers

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} 
        }
    };
like image 118
quantdev Avatar answered Oct 07 '22 00:10

quantdev


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

like image 29
Irrational Person Avatar answered Oct 07 '22 00:10

Irrational Person