Initialize Pointer to Dynamic Array of Struct

I am working through Prata's C++ Primer 5th ed. and am stuck. This is a two-part problem. The first bit of code creates an array of struct, initializes the various bits, and then displays them using a pointer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int main()
{
  using namespace std;
  struct candybar
  {
    char bar_name[15];
    float weight;
    short calories;
  };
  candybar snacks[3] = {{"Mocha Munch", 2.3, 350},
                        {"Cocoa Crush", 4.3, 920},
                        {"What Crap!", 3.7, 512}};
  candybar *p = snacks;
  for (; p < snacks+3; p++)
    cout << "Bar: " << p->bar_name
    << ", Weight: " << p->weight
    << ", Calories: " << p->calories << endl << endl;
  return 0;
}


When I create a standard array of struct "snacks" at compile time, it is very simple and tidy. I can't get my mind around how to initialize a pointer to an array of struct.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
int main()
{
  using namespace std;
  struct candybar
  {
    char bar_name[12];
    float weight;
    short calories;
  };
  candybar *snacks = new candybar[3];
  // How do I get values into each snack?!
  // I know I can do this:

  // snacks[0].weight = 3.5;
  // snacks[0].calories = 250;

  // but to supply all those values one by one
  // seems terribly inconvenient when compared
  // to a regular array of struct:

  // candybar snacks[3] = {{"Mocha Munch", 2.3, 350},
  //                      {"Cocoa Crush", 4.3, 920},
  //                      {"What Crap!", 3.7, 512}};

  delete [] snacks;
  return 0;
}


I would sure appreciate any insight into this puzzle. The research that I dug up around the Net says it can't be done! Here is the exact wording of the question:

"...instead of declaring an array of three candybar structures, use new to allocate the array dynamically."


The trouble is not allocating it; I'm pretty sure I have that bit right. The trouble I have is initializing the values once the array is allocated.
You could create a (member)function to initialize the values:

1
2
3
4
5
6
7
8
void candybar::initialize(char new_bar_name[15],float new_weight, short new_calories)
    {
         
        for (int i=0;i<15;i++) 
            bar_name[i]=new_bar_name[i];
        weight=new_weight;
        calories=new_calories;
    }
Put on a constructor in your struct.
Thank you Scipio and Zaita.

As I suspected, the answers you provided involve subject matter not yet covered in the book. I thought perhaps I had overlooked something, but really I was just overreaching, thinking too far ahead. Hopefully this will become clearer in the upcoming chapters. Meanwhile, I'm still plugging away.

Thanks again for your time.
Topic archived. No new replies allowed.