Can you initialize a dynamic array of structs?

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
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
Ok, so if I wanted to do this, I'd need to assign each member separately? One at a time.
If you write a set function,
1
2
3
4
andyBar *line = new CandyBar[3];
line[0].set("Big", 10, 100);
line[1].set("Bigger", 100, 1000);
line[2].set("Biggest", 1000, 100000);
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
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.
Topic archived. No new replies allowed.