Reputation: 3
The exception I have received was
Exception thrown at 0x70F8516F (vcruntime140d.dll) in Project.exe: 0xC0000005: Access violation writing location 0x723D9C18.
It occurs during the final iteration of user defined information into an array during a for loop:
int k;
cout << "Enter array size:";
cin >> k;
while (k > 3) {
cout << "Array size too big, please reenter" << endl;
cin >> k;
}
Player *ptr = new Player[k];
string n;
int s;
for (int i = 0; k >= i; i++) {
cout << "Enter name" << endl;
cin >> n;
ptr[i].setName(n);
cout << "Enter score" << endl;
cin >> s;
ptr[i].setScore(s);
ptr[i].getName();
ptr[i].getScore();
}
And it directs me to the end of my setName function
void Player::setName(string n) {
name = n;
}
Upvotes: 0
Views: 71
Reputation: 440
You should write
Player *ptr = new Player[k+1];
Suppose your value of k
is 5 then your loop will iterate 6 times (0 to 5) , and you have allocated space only for 5 objects. That's why it will throw an exception.
Upvotes: 0
Reputation: 457
your array size should be (k+1) or the for loop should be like :
for (int i = 0; i<k; i++) {
cout << "Enter name" << endl;
cin >> n;
ptr[i].setName(n);
cout << "Enter score" << endl;
cin >> s;
ptr[i].setScore(s);
ptr[i].getName();
ptr[i].getScore();
}
Upvotes: 1