I have some difficult situation here which I hope some body will help me.
I have the following,
struct CandyBar{
std::string name;
double weight;
int calories;
} ;
Now, for creating an array of structure to contain many CandyBars is much simple which I have done like;
int main(){
CandyBar bars[] = {{"Mango tart", 2.3, 100}, {"Yo Yo", 3.2, 130}, {"Orange Ball", 1.7, 98}};
return 0;
}
But, now I want to create the same structure using new. It is quite simple when I think it but this crashes and does not work.
CandyBar *bars = new CandyBar;
(*bars).name = "Mango tart";
bars->weight = 2.3;
bars->calories = 100;
bars += 1;
(*bars).name = "Yo Yo";
bars->weight = 3.2;
bars->calories = 130;
bars += 1;
(*bars).name = "Orange Ball";
bars->weight = 1.7;
bars->calories = 98;
But, this does not work. As I think that the first pointer is a memory location pointing to the first structure and then I create the structure and then increase the address using bar += 1, and go on creating the pointer but am I missing something really serious.
I would really appreciate your help.
CandyBar.vectororsharedptrsounds like the way to go.std::vector<CandyBar>.(*bars).andbars->? It looks silly. Also, how can you delete the array later, when you've modified the pointer that holds its address?deletein the destructor on something allocated withnew[].