Question about using new on an array of structures.

Hi!

I'm trying to learn C++ on my own using C++ Primer Plus and am stuck on the question in chapter 4.

Do Programming Exercise 6, but, instead of declaring an array of three CandyBar structures, use new to allocate the array dynamically.

The structure CandyBar has a name (string), a weight (double) and calories(int).
And I'm supposed to use new to allocate an array of the structures CandyBar dynamically.

My attempt at a solution:


#include <iostream>
#include <string>

int main ()
{
using namespace std;
struct CandyBar
{
string name;
double weight;
int calories;
};

CandyBar * types = new CandyBar[3];

types =
{
{"Mars", 5, 6},
{"Snickers", 2, 4},
{"Kit Kat", 2, 3}
}

cout << types[0].name << endl;
cout << types[1].weight << endl;
cout << types[2].calories << endl;

delete [] types;

}

However, I get stuck trying to initialize "types" but I don't know what the problem is.

Thanks in advance!

Cheers!
Unicyclist
You should initilize "types" in a simular way to how you display them with the cout command.
Hi!

I don't get what you mean what it should be similar to the display in a cout command.
with a "<<"?

I'm quite new to all of this so any help would be appreciated.

Thanks!

Cheers!
Unicyclist
It means you init your struct like this:

types->name = "Mars";
(types + 1)->weight = 123;

Or you can do without a pointer:

CandyBar types[3] =
{
{"Mars", 5, 6},
{"Snickers", 2, 4},
{"Kit Kat", 2, 3}
};
I stumbled across this because I was having the same problem. Using the member access operator (.) worked for initializing the members of the structures in the array but is there a less tedious way to go about it? I tried using kfgoh's 2nd suggestion but it produces a compiler error when the memory has already been allocated via new before hand.
you do not need to allocate memory using new. Use kfgoh's second example. You cannot use this aggregate initialization if you dynamically allocate using new. Here you are creating an array on the stack of 3 elements. By the way, this only works for POD types. If the struct had a user defined constructor the compiler would reject it.

1
2
3
4
5
6
CandyBar types[3] =
{
{"Mars", 5, 6},
{"Snickers", 2, 4},
{"Kit Kat", 2, 3}
};
Topic archived. No new replies allowed.