Initialize a dynamic array of structures
Jul 28, 2009 at 11:48am UTC
I have been following C++ primer plus by Stephen Prata and am having trouble with an exercise relating to creating a dynamic array of structures. To be more specific initializing the members of the array. Here is the code I have got so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include <iostream>
#include <string>
using namespace std;
struct CandyBar{
string name;
double weight;
double calories;
};
int main()
{
CandyBar* sweet = new CandyBar[3];
sweet = {
{ "Mocha Munchy" , 200, 300 },
{ "Chocolaty Cats" , 490, 100 },
{ "Diabolical Dippers" , 100 200};
};
cout << sweet[0].name << " weighs " << sweet[0].weight << endl;
cout << " and contains only " << sweet[0].calories << "!\n" ;
cout << sweet[1].name << " weighs " << sweet[1].weight << endl;
cout << " and contains only " << sweet[1].calories << "!\n" ;
cout << sweet[2].name << " weighs " << sweet[2].weight << endl;
cout << " and contains only " << sweet[2].calories << "!\n" ;
delete [] sweet;
return 0;
}
This doesn't compile, producing the error message on line 15: "Expected primary expression before { token."
Am I correct in thinking that I need to initialize each member individually?
1 2 3 4 5
CandyBar* sweet = new CandyBar[3];
sweet[0].name = "Mocha Munchy" ;
sweet[0].weight = 200;
sweet[0].calories = 300;
//etc...
Or is there a less tedious way?
Cheers
Jul 28, 2009 at 11:55am UTC
Am I correct in thinking that I need to initialize each member individually?
Yes.
Jul 28, 2009 at 3:21pm UTC
Ok. thanks for the quick reply.
Topic archived. No new replies allowed.