Initialize Dynamic Array of a Struct in C++

Back in 2009 Ganellon [http://www.cplusplus.com/forum/beginner/7295/] asked about an exercise in Prata's C++ Primer Plus, Ch 4, Ex6 covering assignment of values to a dynamic array of a structure. AS Ganellon suggests, responses use techniques not found up to Ch 4. So I'm posting here to update the original posting (now archived, cannot be updated directly).

Prata asks the student to change the following so that the array is dynamic.

Here's my version:
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
#include <iostream>
using namespace std;

const char BRAND_SIZE = 30;

struct CandyBar {
	char Brand[BRAND_SIZE];
	float Weight;
	int Calories;
};

// prototype
void output(CandyBar);

int main(){
	CandyBar snacks[3] = 
	{
		{"Mocha Munch",2.3,350},
		{"Chocoholic",2.5,550},
		{"CherryLucious",3.6,720}
	};
	output(snacks[0]);
	output(snacks[1]);
	output(snacks[2]);
}

void output(CandyBar candybar){
	cout << "\nName: " << candybar.Brand;
	cout << ", Weight: " << candybar.Weight;
	cout << ", Calories: " << candybar.Calories;
}

And here's my solution:
1
2
3
4
5
6
7
8
9
10
11
12
int main(){
	CandyBar *snacks = new CandyBar[3];
	 //snacks is pointer to array
	strcpy(snacks[0].Brand,"Mocha Munch");
	snacks[0].Weight = 2.3;
	snacks[0].Calories = 350;
	strcpy(snacks[1].Brand,"Chocoholic");
	snacks[1].Weight = 2.5;
	snacks[1].Calories = 550;
	strcpy(snacks[2].Brand,"CherryLucious");
	snacks[2].Weight = 3.6;
	snacks[2].Calories = 720;

As you can see strcpy works, and it was a function suggested in the text. Both Brand and each of the strings are pointers to string arrays.
Still, it would be nice to know if a dynamic string array can be initialized.
When you construct the dynamic array every object has to be default initialized using a default constructor. There is no way around that. Even if you used a sequence container to build the dynamic sequence it still wouldn't be possible to initialize all of the elements of each with unique values. I'm not knowledgeable enough about what the capabilities are in the next version of C++ to tell you what you might be able to do with the latest compilers.
By the way, the original link is messed up in the post.
http://www.cplusplus.com/forum/beginner/7295/
Topic archived. No new replies allowed.