I am working through Prata's C++ Primer 5th ed. and am stuck. This is a two-part problem. The first bit of code creates an array of struct, initializes the various bits, and then displays them using a pointer.
When I create a standard array of struct "snacks" at compile time, it is very simple and tidy. I can't get my mind around how to initialize a pointer to an array of struct.
int main()
{
usingnamespace std;
struct candybar
{
char bar_name[12];
float weight;
short calories;
};
candybar *snacks = new candybar[3];
// How do I get values into each snack?!
// I know I can do this:
// snacks[0].weight = 3.5;
// snacks[0].calories = 250;
// but to supply all those values one by one
// seems terribly inconvenient when compared
// to a regular array of struct:
// candybar snacks[3] = {{"Mocha Munch", 2.3, 350},
// {"Cocoa Crush", 4.3, 920},
// {"What Crap!", 3.7, 512}};
delete [] snacks;
return 0;
}
I would sure appreciate any insight into this puzzle. The research that I dug up around the Net says it can't be done! Here is the exact wording of the question:
"...instead of declaring an array of three candybar structures, use new to allocate the array dynamically."
The trouble is not allocating it; I'm pretty sure I have that bit right. The trouble I have is initializing the values once the array is allocated.
As I suspected, the answers you provided involve subject matter not yet covered in the book. I thought perhaps I had overlooked something, but really I was just overreaching, thinking too far ahead. Hopefully this will become clearer in the upcoming chapters. Meanwhile, I'm still plugging away.