using a pointer to point to an array of a stucture

Started by
5 comments, last by rip-off 15 years, 9 months ago
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.
Advertisement
Quote:Original post by mattnenterprise
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.
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.
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.
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....
Quote:Original post by mattnenterprise
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.
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(...));
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)
Peter
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';}

This topic is closed to new replies.

Advertisement