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;
};
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.