using a pointer to point to an array of a stucture

This topic is 3514 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I have been having problems.My code liike like this. CandyBar * ps = new CandyBar[3]; the CandyBar part is a structure.I can't assign any values to the array.

Share on other sites
Quote:
 Original post by mattnenterpriseI have been having problems.My code liike like this.CandyBar * ps = new CandyBar[3];the CandyBar part is a structure.I can't assign any values to the array.
We will need more information. What do you mean by 'you can't assign any values to the array'? Are you getting an error? And if so, what kind of error? Compile-time? Run-time? An assertion? An exception? A crash? How do you know the values aren't being assigned?

Post some more code, along with any error messages you're receiving and/or a description of the observed behavior.

Share on other sites
i am trying to assing values to it like this

ps[0] =
{
"Mocha Munch , 2.3 , 350
};

but it says I need a ; before the first brace when I try to compile it
can someone tell me what I'm doing wrong.

Share on other sites
make sure you are accessing them correctly...ie

ps[0].yummy = true;
ps[0].cost = $1.75 ps[1].yummy = false; ps[1].cost =$100

etc....

Share on other sites
Quote:
 Original post by mattnenterprisei am trying to assing values to it like thisps[0] = { "Mocha Munch , 2.3 , 350}; but it says I need a ; before the first brace when I try to compile itcan someone tell me what I'm doing wrong.
Bracket notation can only be used to initialize, not to assign.

Here is an example of how this might be written in idiomatic C++:
std::vector<CandyBar> = boost::assign::list_of    (CandyBar("Mocha Munch", 2.3, 350))    (CandyBar(...))    (CandyBar(...));

Share on other sites
Or you could make a constructor to your structure and then assign the values like this:

ps[0] = CandyBar(true, 1.75)
ps[1] = CandyBar(false, 100)

Share on other sites
You are using initialisation syntax, but the struct has already been initialised. The easiest way would be to write an explicit constructor, and to use std::vector instead of new[], delete[] pairs:
struct CandyBar{    std::string name;    float cost;    int sugaryGoodness;    CandyBar(const std::string &name, float cost, int goodness)    :        name(name),        cost(cost),        sugaryGoodness(goodness)    {    }};// in whatever functionvoid foo(){    std::vector<CandyBar> bars;    bars.push_back(CandyBar("Mocha Munch" , 2.3 , 350));    // can access like an array    std::cout << bars[0].name << '\n';}