我收到的例外是
Exception thrown at 0x70F8516F (vcruntime140d.dll) in Project.exe: 0xC0000005: Access violation writing location 0x723D9C18.
在for循环期间将用户定义信息最终迭代到数组期间发生:
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();
}
它指示我到我的setName函数的结尾
void Player::setName(string n) {
name = n;
}
答案 0 :(得分:1)
你的数组大小应该是(k + 1),或者for循环应该是:
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();
}
答案 1 :(得分:0)
你应该写
Player *ptr = new Player[k+1];
假设您的k
值为5,那么您的循环将迭代6次(0到5),并且您只为5个对象分配了空间。这就是它会抛出异常的原因。