Search code examples
c++arraysstructureheap-memory

Creating an Array of Structures on the Heap in C++


I need to declare an array of structures on the heap, then transfer data from parallel arrays on the stack and from calculations into each structure. I declared

struct Grades
{
    string  studentName;
    int     scores[4];
    double  average;
};

....

Grades *art1301 = new Grades;

....

(art1301 + i)->studentName = names[i];

for((int i = 0 ; i < 5 ; i++ )
(art1301 + i)->scores[j] = exams[i][j];

(art1301 + i)->average = average; 

My program accesses the first record, but it crashes after it accesses the first field of the second record. I don't understand why it works for the first record, but dies in the middle of the second? Am I accessing the structure correctly?

Thank you.


Solution

  • To allocate an array, you need the array form of new, with the square brackets:

    Grades *art1301 = new Grades[200];
    //                          ^^^^^
    

    The array size can be a dynamically determined quantity.