c++ - 在循环期间收到 "Exception Thrown"

标签 c++

我收到的异常是

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();

}

关于c++ - 在循环期间收到 "Exception Thrown",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41196913/

相关文章:

c++ - 函数和多类层次结构

c++ - Cocos2d Portrait Mode 对象位置搞砸了

c# - 包含 atlbase.h header 时应用程序崩溃

c++ - 为函数定义符号不明确的指针参数

c++ - 消除 QLabel 顶部的间隙

c++ - C/C++字符串内存分配

c++ - 汇编 VMOVD 的 C/C++ 内在函数

c++ - 将一行(字符串)拆分成更多的字符串

c++ - 使用 UNREFERENCED_PARAMETER 宏

c++ - 在自定义类中重载 ostream 运算符