I assume
testScores is a local variable? In that case, yes, it's because you're overwriting in memory.
Lets say we have
testScores an array at location 0x1234. On the first loop your array contains [1,2,3,4]. You go
studentArray[0].setTestScores(0x1234)
, so
studentArray[0] contains [1,2,3,4] - that is, the memory at 0x1234.
On the next iteration, you set
testScores to be [5,6,7,8]. That is, the memory at 0x1234 now contains [5,6,7,8]. Once again, you go
studentArray[1].setTestScores(0x1234)
, so
studentArray[1] contains [5,6,7,8] - that is, the memory at 0x1234.
But wait! What about
studentArray[0]? It's just pointing to 0x1234, so now it too has contents [5,6,7,8]! Oops.
Basically, what you need to do is to get each
studentArray to have it's
own array; that is, its own memory location. You may do it something like this:
1 2 3 4 5 6 7 8 9 10 11 12
|
class Student {
// local array; our own bit of memory for the scores.
int testScores[NUM_SCORES];
public:
// ...
void setTestScores(int* scores) {
// copy the data across to our memory
for (int i = 0; i < NUM_SCORES; ++i)
testScores[i] = scores[i];
}
};
|
Another option is to use a
std::vector for your arrays; it will deal with all this pointer nonsense for you behind the scenes, and as an added bonus allows dynamic array length.