SO I'm very new to c++ (as in a few weeks) and I've been reading the C++ Primer Plus by Stephen Prata. At the end of each chapter he outlines programming exercises. The one I'm stuck on involves using new to create a dynamic array. Here's the code
#include <iostream>
#include <string>
void tag(int);
usingnamespace std;
struct candybar
{
char name[20];
double weight;
int calories;
};
int main()
{
tag(0);
tag(1);
tag(2);
return 0;
}
void tag(int n)
{
candybar *pc = new candybar [3];
pc[0] = {"Mars" , 2.75, 245}; //Error on this line
pc[1] = {"Butterfinger", 2.85, 300}; //Error on this line
pc[2] = {"Twix", 2.12, 150}; //Error on this line
cout << "The Candy Company is releasing a new treat called " << pc[n].name << " which weighs a total of " << pc[n].weight ;
cout <<" pounds and only contains " << pc[n].calories << " calories.\n";
};
I'm using Visual Studio Express 2012 and I'm getting the build error "Error C2059: syntax error : '{'" and intellisense is telling me it "expected an expression." I could use some help understanding this, thanks in advance.
You can only use the {}-syntax to initialize the object when the object is created. When creating an array with new candybar [3] the objects in the array will be default initialized, and in C++03 there is no way around this.
Instead of pc[0] = {"Mars" , 2.75, 245};
do would have to do something like:
You need to delete[] the array before you return from tag(), or else there would be a leak.
Better still, just use a std::vector<> instead http://www.mochima.com/tutorials/vectors.html
#include <iostream>
#include <string>
#include <vector> // *** added
void tag(int);
usingnamespace std;
struct candybar
{
std::string name; // *** changed
double weight;
int calories;
};
int main()
{
tag(0);
tag(1);
tag(2);
}
void tag(int n)
{
//candybar *pc = new candybar [3];
std::vector<candybar> pc(3) ; // dynamic array of 3 candybars
candybar a = {"Mars" , 2.75, 245}; pc.push_back(a) ;
candybar b = {"Butterfinger", 2.85, 300}; pc.push_back(b) ;
candybar c = {"Twix", 2.12, 150}; pc.push_back(c) ;
cout << "The Candy Company is releasing a new treat called " << pc[n].name
<< " which weighs a total of " << pc[n].weight ;
cout <<" pounds and only contains " << pc[n].calories << " calories.\n";
}
void tag_1(int n) // or
{
candybar *pc = new candybar [3];
candybar a = {"Mars" , 2.75, 245}; pc[0] = a ;
candybar b = {"Butterfinger", 2.85, 300}; pc[1] = b ;
candybar c = {"Twix", 2.12, 150}; pc[2] = c ;
cout << "The Candy Company is releasing a new treat called " << pc[n].name
<< " which weighs a total of " << pc[n].weight ;
cout <<" pounds and only contains " << pc[n].calories << " calories.\n";
delete[] pc ;
}