访问数组时出错 - 变量“得分”周围的堆栈已损坏

时间:2014-05-06 21:38:24

标签: c++ arrays indexoutofboundsexception

我是C ++的新手并编写了一些代码,其中我收到了以下错误:

  

运行时检查失败#2 - 围绕变量'得分'被腐蚀了

导致此错误的原因是什么?

这是我的代码:

#include <iostream> // Enables cout and endl
#include <string>
#include <sstream>
#include "stdafx.h"

using namespace std;
int getInput();

int main()
{
    int scores[5];
    int i;
    int j;
    int numberOfScores;

    for (i = 0; i < 6; i++) // Sets all 5 elements of the array to zero
    {
        scores[i] = 0;
    }

    cout << "How many scores do you have to enter?\n" << endl;
    cin >> numberOfScores;


    for (j = 0; j < numberOfScores; j++) // Gather test scores and increases each array index as that score is entered
    {
        scores[getInput()] ++;
    }

    cout << "The number of zeros: " << scores[0] << endl;
    cout << "The number of ones: " << scores[1] << endl;
    cout << "The number of twos: " << scores[2] << endl;
    cout << "The number of threes: " << scores[3] << endl;
    cout << "The number of fours: " << scores[4] << endl;
    cout << "The number of fives: " << scores[5] << endl;


    return 0;
}

int getInput()
{
    int enteredScore;
    cout << "Enter the test scores one at a time.\n";
    cout << "The range of scores is 0 to 5.\n";
    cin >> enteredScore;

    if (enteredScore >= 0 && enteredScore <= 5)
    {
        return enteredScore;
    }
    else
    {
        cout << "Error!  The range of scores is 0 to 5.\n";
        cout << "Enter the test scores one at a time.\n";
        cin >> enteredScore;
        return enteredScore;
    }
}

3 个答案:

答案 0 :(得分:5)

似乎这个声明:

int scores[5];

不正确。这将创建一个包含5个数字的数组,来自scores[0-4]的索引,但是,在整个程序中,您经常引用数组的{{1>},第六个元素。我建议改为

score[5]

答案 1 :(得分:1)

问题:

您正在多个地方访问您的阵列。

当你只有5:

时,你循环浏览6个元素
for (i = 0; i < 6; i++) // Loops through 6 elements
    {
        scores[i] = 0;
    }

在这里,您可以调用getInput()并使用返回值作为索引:

scores[getInput()] ++;

但是,函数的前半部分接受来自用户的输入,范围为0到5,因此允许访问6个元素:

if (enteredScore >= 0 && enteredScore <= 5)

如果用户输入超出该范围的数字,情况会变得更糟,因为他们会有第二次输入数字的机会,但这次没有验证,他们输入的任何数字都被接受:

cin >> enteredScore;
return enteredScore;

最后,您再次尝试访问第6个元素:

cout << "The number of fives: " << scores[5] << endl;

<强>解决方案:

首先,您需要做以下两件事之一:

  • 更改for循环,if语句和cout语句,以便它们不会访问索引5

或:

  • 创建数组,使其具有6个元素:int scores[6];

其次,您需要修复getInput()函数中的错误,以便正确验证输入。你可以试试这个例子:

int getInput()
{
    int enteredScore;
    cout << "Enter the test scores one at a time.\n";
    cout << "The range of scores is 0 to 4.\n";
    cin >> enteredScore;

    while (enteredScore < 0 || enteredScore > 4)
    {
        cout << "Error!  The range of scores is 0 to 4.\n";
        cout << "Enter the test scores one at a time.\n";
        cin >> enteredScore;
    }
    return enteredScore;
}

答案 2 :(得分:0)

中有错误
 cout << "The number of fives: " << scores[5] << endl;

您的数组大小为5,但您正在访问第6个元素。

for (i = 0; i < 6; i++)相同,应为i < 5