When dynamically allocating an array of structures can I still somehow initialize them as before with code something like this?
candybar snack[3] = { {"Mocha", 2.3, 250}, {"Twist", 4.8, 125}, {"Toffee", 8.2, 65} };
I Googled it and apparently someone else had the same problem with this exercise and came up with this solution but the code is so much longer that before and I was wondering if this is the shortest way to accomplish this.
#include <iostream>using namespace std;int main(){struct CandyBar //struct declaration{char *brand;float weight;int calories;};//dynamic array declarationCandyBar *Candies = new CandyBar[3];CandyBar *CandyPointer = &Candies[0]; //pointer to a CanyBar data object//structure initialization one by one(*CandyPointer).brand = "Mocha Munch";CandyPointer->weight = 2.3;CandyPointer->calories = 350;CandyPointer = &Candies[1];(*CandyPointer).brand = "Chilly Willy";CandyPointer->weight = 2.2;CandyPointer->calories = 200;CandyPointer = &Candies[2];(*CandyPointer).brand = "Lemon Rush";CandyPointer->weight = 2.1;CandyPointer->calories = 200;//data output to the screen//first element of the arrayCandyPointer = &Candies[0];cout << "Name of Candy Bar: " << (*CandyPointer).brand << endl;cout << "Weight of Candy Bar: " << CandyPointer->weight << endl;cout << "Number of calories in Candy Bar: " << CandyPointer->calories << "\n\n";//second element of the arrayCandyPointer = &Candies[1];cout << "Name of Candy Bar: " << (*CandyPointer).brand << endl;cout << "Weight of Candy Bar: " << CandyPointer->weight << endl;cout << "Number of calories in Candy Bar: " << CandyPointer->calories << "\n\n";//third element of the arrayCandyPointer = &Candies[2];cout << "Name of Candy Bar: " << (*CandyPointer).brand << endl;cout << "Weight of Candy Bar: " << CandyPointer->weight << endl;cout << "Number of calories in Candy Bar: " << CandyPointer->calories << "\n\n";cin.get();return 0;}
Is this the shortest solution to this problem?
Thanks in advance