Dynamic Struct Array w/ New

I have two questions here , I did the homework assignment in its entirety but I'm wondering if there is an easier way to assign the values to my dynamic array? Is there a reason why I can't use the syntax cArray = { {array1values}, {array2values}, {array3values} }; ?

My compiler kept giving me an error but I didn't understand it.

Also in my for loop it uses the notation : cArray[i].name etc... why isn't it cArray->[i].name ? Is it because an array is an address so an array of structs is really an array of addresses which hold values - and in order to obtain the value at an array index you use bracket notation such as arrayName[i] ? Am I way off? I feel like I'm in over my head with these exercises.

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
33
34
//Chapter 4 Exericse 9
/*
Do exercise 6 but with a dynamic array using new
*/
#include <iostream>
#include <cstring>
using namespace std;

struct CandyBar { char name[20]; double weight; int calories; };

int main()
{
    //dynamic allocation for CandyBar array
    CandyBar * cArray = new CandyBar[3];
    strcpy(cArray[0].name, "Mocha Munch");
    cArray[0].weight = 2.3;
    cArray[0].calories = 250;
    strcpy(cArray[1].name, "Haha Bar");
    cArray[1].weight = 3.0;
    cArray[1].calories = 300;
    strcpy(cArray[2].name, "Real Life?");
    cArray[2].weight = 5.0;
    cArray[2].calories = 5000;
    cout.setf(ios_base::fixed, ios_base::fixed);
    for (int i = 0; i < 3; i++)
    {
        cout << cArray[i].name << " \n";
        cout.precision(2);
        cout << cArray[i].weight << " " << cArray[i].calories << "\n";
    }

    delete [] cArray;
    return 0;
}
Last edited on
You can use that syntax to initialize your array if you don't use a dynamic array.
CandyBar cArray[] = {{"Mocha Munch", 2.3, 250}, ...

If cArray is a pointer cArray[i] is just the same as writing *(cArray + i). I guess it's just convenient to be able to use the same syntax for a pointer as you do with an array.
You can use that syntax but you need a compiler that supports the C++ 2011 Standard.
Ah okay - so that's what c++0x "unsupported" meant... I thought it was some strange sort of bug from my code :X
Topic archived. No new replies allowed.