Allocating and Array with "new"

Hi. Could someone show me how to use "new" to allocate an array for the following stucture:
Thanks

CODE

#include <iostream>
using namespace std;

struct Pizza
{
char name[20];
float diameter;
float weight;
};


int main()
{


...



return 0;
}
Last edited on
You'd be better off using dynamic sequence containers. There is no need to worry about memory leaks if you create one of those like so.
std::deque<Pizza> pizzas(numPizzas); // using deque
std::list<Pizza> pizzaList(numPizzas); // using linked list
std::vector<Pizza> pizzaArray(numPizzas); // pizza array - data is contiguous like c-array
I'm sorry, I just don't understand anything in the links or the last post.

I'll try to make this a little more clear... I'm using a book "C++ Primer Plus" 4th Edition. At the end of Chapter 4 there are some programming excercises to do. The 3rd programming exercise is:

3. The CandyBar structure contains three members, as described in Programming excercise 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.



Ok, I got through excersize 3 OK. The excercise that I'm doing now, is number 6, which is:

6. Do programming excercise 3, but, instead of declaring an array of three CandyBar structures, use new to allocate the array dynamically.



The book doesn't give a direct example of how to do this, and I'm not the best at visualizing stuff...
Last edited on
The links provide examples
OK, I got the basic idea..

I came up with a simple program that I believe fulfills the excercise, in the following code. However, I'm not sure I understand how "new" works..

How was "new" used ?


#include <iostream>
using namespace std;

struct Pizza
{
char name[20];
float diameter;
float weight;
};


int main()
{


Pizza * Pt = new Pizza[10];


cout << "Enter the name of a company \n\n";

cin.getline(Pt[0].name, 20);

cout << "Enter diameter \n\n";
cin >> Pt[0].diameter;

cout << "Enter weight \n\n";
cin >> Pt[0].weight;


cout << Pt[0].name << "\n\n";

cout << Pt[0].diameter << "\n\n";

cout << Pt[0].weight << "\n\n";

delete[] Pt;


return 0;
}





Last edited on
I did a little more reading... I get it now .... thanks for all help
Topic archived. No new replies allowed.