C++ 访问变量';周围的数组堆栈时出错;分数';腐败
运行时检查失败#2-变量“分数”周围的堆栈已损坏 是什么导致了这个错误 这是我的密码:C++ 访问变量';周围的数组堆栈时出错;分数';腐败,c++,arrays,indexoutofboundsexception,C++,Arrays,Indexoutofboundsexception,运行时检查失败#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;
#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;
}
}
#包括//启用cout和endl
#包括
#包括
#包括“stdafx.h”
使用名称空间std;
int getInput();
int main()
{
智力得分[5];
int i;
int j;
整数分数;
for(i=0;i<6;i++)//将数组的所有5个元素设置为零
{
分数[i]=0;
}
考分数;
对于(j=0;j
cout << "The number of fives: " << scores[5] << endl;
cout似乎这个声明:
int scores[5];
不正确。这将创建一个包含5个数字的数组,索引来自分数[0-4]
,但是,您在整个程序中不断引用数组的第六个元素分数[5]
。我建议更改为
int scores[6];
问题:
您在多个位置越界访问阵列
在这里,当您只有5个元素时,可以循环使用6个元素:
for (i = 0; i < 6; i++) // Loops through 6 elements
{
scores[i] = 0;
}
但是,函数的前半部分接受用户在0到5范围内的输入,因此允许访问6个元素:
if (enteredScore >= 0 && enteredScore <= 5)
最后,再次尝试访问此处的第6个元素:
cout << "The number of fives: " << scores[5] << endl;
for(i=0;i<6;i++)
应该是for(i=0;i<5;i++)
,否则它将访问分数[5],由于基于0的索引(0、1、2、3、4是有效的,这是您请求存储的5个元素),分数被一一关闭。请在询问之前进行调试!他实际上正在访问索引5!很抱歉没有首先进行调试-老实说,我还不知道如何进行调试。我尝试过(在Visual Studio中),但没有发生任何事情。很抱歉。无论如何,int分数[6]做了我想做的。@sparky注意,这本身不足以解决问题,因为您也没有正确验证用户输入。
cin >> enteredScore;
return enteredScore;
cout << "The number of fives: " << scores[5] << endl;
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;
}