0

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.

4
  • Here's a hint: This is wrong (for your purposes): Grades *art1301 = new Grades; Commented Apr 28, 2012 at 22:10
  • You are declaring only one Grades struct on the heap. You do not have enough memory allocated for more than one, so you probably get a writing violation consequentially. To be able to work one more than one Grades on the heap, then this change should be made Grades* art1301 = new Grades[i+1], where I assume i + 1 is the number of structs you want allocated. Commented Apr 28, 2012 at 22:10
  • Please don't use pointer arithmetic to index an array. Use the indexing operator []. Commented Apr 28, 2012 at 22:19
  • Thank you, Alex. I thought that was the wrong way to declare the structure, but every way I tried to edit it, the compiler rejected. Commented Apr 28, 2012 at 22:21

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Adding the array size put the entire program working. My assignment is now complete.
0

You aren't allocating memory for an array, you are allocating only for one element.

As someone said in the comments, the key is in the new Grades instruction

In addition, unless you have another i variable declared before (which is a bad practice), that code doesn't compile because (art1301 + i)->studentName = names[i]; will not find variable i

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.