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;
}
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].
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.
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.
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.
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}
}
};
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With