运行此特定功能后,为什么我的程序崩溃了?

时间:2012-10-13 21:24:57

标签: c++ crash runtime

每当我输入命令在我的程序中运行此函数时,它会运行然后崩溃说:

“应用程序已请求Runtime以不常用的方式终止它。”

为什么会这样做?

void showInventory(player& obj) {
    std::cout << "\nINVENTORY:\n";
    for(int i = 0; i < 20; i++) {
        std::cout << obj.getItem(i);
        i++;
        std::cout << "\t\t\t" << obj.getItem(i) << "\n";
    }
}

std::string getItem(int i) {
        return inventory[i];
    }   

4 个答案:

答案 0 :(得分:1)

在此代码中:

std::string toDo(player& obj) //BY KEATON
{
    std::string commands[5] =   // This is the valid list of commands.
    {"help", "inv"};

    std::string ans;
    std::cout << "\nWhat do you wish to do?\n>> ";
    std::cin >> ans;

    if(ans == commands[0]) {
        helpMenu();
        return NULL;
    }
    else if(ans == commands[1]) {
        showInventory(obj);
        return NULL;
    }
}

需要:

std::string toDo(player& obj) //BY KEATON
{
    std::string commands[5] =   // This is the valid list of commands.
    {"help", "inv"};

    std::string ans;
    std::cout << "\nWhat do you wish to do?\n>> ";
    std::cin >> ans;

    if(ans == commands[0]) {
        helpMenu();
        return "";
    }
    else if(ans == commands[1]) {
        showInventory(obj);
        return "";          // Needs to be '""'
    }
}

归功于Prototype Stark!

答案 1 :(得分:0)

当i = 19时,你得到数组中的最后一项,之后我变为20,并且还有另一个getItem,它应该导致越界异常

答案 2 :(得分:0)

for(int i = 0; i < 20; i++) {
    std::cout << obj.getItem(i);

这不是很正确。不要使用魔术数字。而不是20使用int listSize = obj.ListSize()(将由你实现)

listSize = obj.ListSize();
    for(int i = 0; i <listSize ; i++) {
        std::cout << obj.getItem(i);

通过这种方式,您将确保自己不会超出范围。

另外,如果你想在一个循环中打印2个项目(我不明白为什么),你可以这样做:

void showInventory(player& obj) {   // By Johnny :D
    std::cout << "\nINVENTORY:\n";
    int listSize = obj.ListSize()/2; //if you are sure that is odd number
    for(int i = 0; i < listSize; ++i) {
        std::cout << obj.getItem(i);
        i++;
        std::cout << "\t\t\t" + obj.getItem(i) + "\n";
    }
} 

答案 3 :(得分:0)

写一个函数:

class player{
public:
//--whatever it defines 
int ListSize()
{
   return (sizeof(inventory)/sizeof(inventory[0]));
}
};

然后使用

void showInventory(player& obj) {   // By Johnny :D
    int length = obj.ListSize();
    std::cout << "\nINVENTORY:\n";
    for(int i = 0; i < length; i++) {
        std::cout << obj.getItem(i);
        i++;
        std::cout << "\t\t\t" << obj.getItem(i) << "\n";
    }
}