C++ Primer Plus Programming Exercises Help

drgh0st

Limp Gawd
Joined
Aug 26, 2003
Messages
310
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

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.
 
Yeah, you would do CandyBar* snack = new CandyBar[3], just like you would do with a dynamically allocated array of integers.

Just remember to throw in a

Code:
delete[] snack;

I think there is a way to initialize the members, but I haven't the foggiest idea how to. 8(

Only because...

C:\Documents and Settings\Admin\Desktop>g++ -Wall -W test.cpp -o test.exe
test.cpp: In function `int main()':
test.cpp:27: warning: new initializer lists extension is deprecated, please see

the documentation for details

C:\Documents and Settings\Admin\Desktop>
 
Yeah that's what I thought but I can't initialize anything. hmmm... I don't know, I'm gonna surf around and see what I can find.
 
Back
Top