Jan 7, 2011 at 3:08am UTC
Can you initialize a dynamic array of structs. Like in this program. If you can how do you do it.
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
struct CandyBar{
char BrandName[20];
float Weight;
int Calories;};
int main()
{
using std::cout;
using std::cin;
//Can I initialize this dynamic array, or do I have to type it all out?
// The following method won't work. Why? Is it because one statement has 2 assignment operators?
/*CandyBar *line = new CandyBar[3] =
{"Big", 10, 100},
{"Bigger", 100, 1000},
{"Biggest", 1000, 100000}};*/
cout << "CandyBar line\n"
<< "Name: " << line[0]->BrandName
<< "\nWeight: " << line[0]->Weight
<< "\nCalories: " << line[0]->Calories
<< "\n\n" ;
cout << "CandyBar line\n"
<< "Name: " << line[1]->BrandName
<< "\nWeight: " << line[1]->Weight
<< "\nCalories: " << line[1]->Calories
<< "\n\n" ;
cout << "CandyBar line\n"
<< "Name: " << line[2]->BrandName
<< "\nWeight: " << line[2]->Weight
<< "\nCalories: " << line[2]->Calories
<< "\n\n" ;
return 0;
Last edited on Jan 7, 2011 at 3:08am UTC
Jan 7, 2011 at 1:21pm UTC
You can't do that. You could write a default constructor, but then all objects would be the same. You'll have to write it all. pro tip: write a set method.
the = {...} only works for array and object (without constructor) initialization. Think of new as a function which returns a pointer. Initialization happens before it returns.
Last edited on Jan 7, 2011 at 1:23pm UTC
Jan 7, 2011 at 2:17pm UTC
Ok, so if I wanted to do this, I'd need to assign each member separately? One at a time.
Jan 7, 2011 at 5:17pm UTC
With a constructor (not the default)
starting here
http://www.cplusplus.com/forum/general/33536/#msg180653
1 2 3 4 5 6
CandyBar *array;
allocator<CandyBar> aloc;
array = aloc.allocate(n);
aloc.construct( array+0, CandyBar("Big" , 10, 100) );
aloc.construct( array+1, CandyBar("Bigger" , 100, 1000) );
aloc.construct( array+2, CandyBar("Biggest" , 1000, 100000) );
(emulating std::vector)
Last edited on Jan 7, 2011 at 5:19pm UTC
Jan 7, 2011 at 6:13pm UTC
Ok, thanks. I didn't even think about making a function to set it for me.. I don't think the book I'm following has gotten to the part where we learn about how to create structure methods yet.