[英]Receiving an “Exception Thrown” during loop
我收到的例外是
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;
}
您的數組大小應為(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();
}
你應該寫
Player *ptr = new Player[k+1];
假設k
值為5,則循環將迭代6次(0到5),並且您僅為5個對象分配了空間。 這就是為什么它將引發異常的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.