Structure with arrays

Nov 28, 2012 at 10:08pm
So this might not even exist but if it doesn't it definitely should. I have 3 arrays of structures that i would like to display their individual elements. I would use a 2D array but the structure holds multiple different types.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
struct candyBar
{
        char brandName[20];
        double weight;
        int calories;
};

int main (void)
{
        //initialize the type candyBar variable  
        candyBar snack[3] =
        {
                "Mocha Munch",
                2.3,
                350,
        };
        
        candyBar snack1[3] =
        {
                "Snickers",
                3.2,
                600,
        };

        candyBar snack2[3]
        {
                "Milky Way",
                4.1,
                320,
        };


this is an exercise from c++ primer 6th ed chapter 4 problem 6

I would like to have it so that this program could be expanded to as large as i would ever want. So variables and loops are my main goals obviously.
Last edited on Nov 28, 2012 at 10:15pm
Nov 28, 2012 at 10:40pm
closed account (D80DSL3A)
Did you have any trouble with the exercises in chapter 3?

What you posted is kinda nonsense. Try backing up in your textbook.
EDIT: What is this problem #6?
Last edited on Nov 28, 2012 at 10:41pm
Nov 28, 2012 at 10:43pm
http://www.cplusplus.com/forum/articles/1295/

You haven't provided us with an actual question. But the code you have provided above is incorrect.

 
candyBar snack[3] = // Etc 

Creates an array to hold 3 snack objects, but you're only defining 1. I'd be surprised if this code compiled.

C++11 would have something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
candyBar snack[3] = { 
        {
                "Mocha Munch",
                2.3,
                350,
        },
        {
                "Snickers",
                3.2,
                600,
        },
        {
                "Milky Way",
                4.1,
                320,
        }
};

Last edited on Nov 28, 2012 at 10:44pm
Nov 28, 2012 at 10:56pm
@ Zaita so you can put the snack in the array and reference them. snack[0].name = "Mocha Munch

ahhh once you posted that i remembered seeing it and found that type of assigning thanks for the help!
Topic archived. No new replies allowed.