Hi all
I'm trying to create a dynamic array of structures and have come across the following code but I can't figure out how some of it works: (incidentally this is from Prata's book C++ Primer Plus, Ch4, Ex.9)
#include <iostream>
using namespace std;
int main()
{
//structure declaration
struct CandyBar
{
char brand[20];
float weight;
int calories;
};
//dynamic array declaration
CandyBar *Candies = new CandyBar[3];
//create pointer to the first CandyBar structure within the array
CandyBar *CandyPointer = &Candies[0];
//structure initialization one by one
(*CandyPointer).brand = "Mocha Munch";
CandyPointer->weight = 2.3;
CandyPointer->calories = 350;
<snipped code>
return 0;
}
As far as I can understand - line 15
CandyBar *Candies = new CandyBar[3];
creates a pointer (Candies) which contains the address of the first element in the array (which in this case is a structure of CandyBar type)
line 18
CandyBar *CandyPointer = &Candies[0];
creates a pointer (CandyPointer) which points to the address of the previous pointer when it's pointing at the first element.
Why do we need this second pointer to initialise the array elements, rather than using the first pointer?
e.g.
CandyBar *Candies = new CandyBar[3];
Candies[0] = {"Violent Crumple", 20.5, 7000};
which I know doesn't work (syntax error) - but why not??
Thanks a lot
cobberas