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

Error when accessing array - stack around the variable 'scores' was corrupted

本文关键字:分数 周围 堆栈 已损坏 变量 数组 出错 访问      更新时间:2023-10-16

我是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;
    }
}

似乎这个声明:

int scores[5];

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

int scores[6];

问题:

您在多个地方访问了超出范围的数组。

在这里,当你只有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;

最后,您再次尝试访问此处的第六个元素:

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;
}

中有一个错误

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

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

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