I'm trying to refresh myself and I'm stuck on this problem (not homework/school related but for personal advancement).
6: Do programming exercise 3, but, instead of declaring an array of three CandyBar structures, use new to allocate the array dynamically.
That's the question in case you guys don't ahve the book. I have Exercises 3 done and I can properly use structures. But I'm not sure how to use it for 6. Here's problem 3 solved
would I do this??
CandyBar * snack = new Candybar[3];
I'm kinda stuck. any help would be appreciated. This book goes over using new wiht arrays and new with structures but I'm not quite sure how to bring the two together. Thanks.
6: Do programming exercise 3, but, instead of declaring an array of three CandyBar structures, use new to allocate the array dynamically.
That's the question in case you guys don't ahve the book. I have Exercises 3 done and I can properly use structures. But I'm not sure how to use it for 6. Here's problem 3 solved
Code:
// C++ Primer Plus
// chapter 4
// Programming Exercises
// 3: The CandyBar structure contains three members, as described in Programming Exercise 2. Write a program that creates an array of three CandyBar
// structures, initializes them to values of your choice, and then displays the contents of each structure.
// Author: Steven C. Eng
// Last Revisited: 12.30.03
#include <iostream>
using namespace std;
struct CandyBar
{
char brandname[20];
double weight;
int calories;
};
int main()
{
CandyBar snack[3] =
{
{"Mocha Munch", 2.3, 350},
{"Chocolate Hurricane", 2.4, 400},
{"Hersey", 2.5, 450}
};
cout << "Brand name of candy bar: " << snack[0].brandname << "\n";
cout << "Weight of candy bar: " << snack[0].weight << "\n";
cout << "Calories of candy bar: " << snack[0].calories << "\n";
cout << "\n";
cout << "Brand name of candy bar: " << snack[1].brandname << "\n";
cout << "Weight of candy bar: " << snack[1].weight << "\n";
cout << "Calories of candy bar: " << snack[1].calories << "\n";
cout << "\n";
cout << "Brand name of candy bar: " << snack[2].brandname << "\n";
cout << "Weight of candy bar: " << snack[2].weight << "\n";
cout << "Calories of candy bar: " << snack[2].calories << "\n";
}
would I do this??
CandyBar * snack = new Candybar[3];
I'm kinda stuck. any help would be appreciated. This book goes over using new wiht arrays and new with structures but I'm not quite sure how to bring the two together. Thanks.