Search code examples
c++dynamicheap-memory

Correct syntax to access array elements in structs?


First-year comp sci student, and first time posting on here.

I have a struct:

struct Student{
    string name;
    int studentID;
    int numTests;
    int *testScores = new int [TESTS]; //Access with <variableName>.*(testScores + 1), <variableName>.*(testScores + 2), etc.
    int avgScore;
};

I'm having trouble trying to figure out how to change the values in the array. I guess I can't figure out the syntax.

This is what I'm doing, am I on the right track?

cout << "How many tests did this student take: ";
cin >> numTests;

//iterate numTests amount of times through dynamic array
for (int i = 0; i < numTests; ++i)
{
    cout <<"Enter score #" << i + 1 << ": ";
    cin >> tempScore;
    newStudent.*(testScores + i) = tempScore;
}    

I'd appreciate any help in figuring out the right way to go about changing the arrays values.

I've tried not using the temp value, changing it to

cin >> newStudent.*(testScores + i);

along with

cin >> *newStudent.(testScores + i);

and a few other variations, but I can't seem to find out the correct way to go about it. Still new to working with the heap.


Solution

  • Firstly, "reference array" is a surprising way to describe testScores. The testScores data member in your struct has type "pointer to int" and presumably points to the first element in the array you have allocated with a new expression.

    Secondly, you access elements in that array by doing

    newStudent.testScores[i] = tempScore;
    // which is equivalent to ...
    *(newStudent.testScores + i) = tempScore;
    

    You can also write

    std::cin >> newStudent.testScores[i];
    

    ... bypassing the need for an extra local tempScore variable.

    Further Notes