[英]Why does this c++ program cause a system crash?
#include <iostream>
using namespace std;
int main()
{
int nums[20] = { 0 };
int a[10] = { 0 };
cout << a << endl;
cout << nums << endl;
cout << "How many numbers? (max of 10)" << endl;
cin >> nums[0];
for (int i = 0; i < nums[0]; i++)
{
cout << "Enter number " << i << endl;
cin >> a[i];
}
// Output the numbers entered
for (int i = 0; i < 10; i++)
cout << a[i] << endl;
return 0;
}
If this program is run and we enter 255 for how many numbers, and 9 for every single number, it causes it to crash. 如果运行此程序,然后输入255作为数字,每个数字输入9,它将导致程序崩溃。
Its because int a[10] = { 0 };
这是因为int a[10] = { 0 };
and you try to index it past the 10th cell or location 9. You need to fix your for loop 并尝试将其索引到第10个单元格或位置9之后。您需要修复for循环
for (int i = 0; i < nums[0]; i++)
{
cout << "Enter number " << i << endl;
cin >> a[i];
}
or change the length of your cell in intialization 或更改初始化的单元格长度
Why does your program crash? 为什么程序崩溃? You've only allocated 10 elements for a
. 你只分配了10元a
。
You tell the user "(max of 10)"
. 您告诉用户"(max of 10)"
。 The user ignores this and types in 255
. 用户忽略此内容并输入255
。 You need to check that the user has listened to your warning before doing anything else. 在执行其他任何操作之前,您需要检查用户是否已听完您的警告。
cout << "How many numbers? (max of 10)" << endl;
cin >> nums[0];
// Has the user listened to your warning?
if (nums[0] > 10) {
cout << "Bad input!" << endl;
return 0;
}
You are using nums[0]
as the max bound for the loop 您正在使用nums[0]
作为循环的最大界限
for (int i = 0; i < nums[0]; i++)
{
cout << "Enter number " << i << endl;
cin >> a[i];
}
In your case you are doing 255 loops and in each iteration you add the value into a[i]
. 在您的情况下,您要进行255次循环,并且在每次迭代中,请将值添加到a[i]
。
You declared the array a
to have a size of 10 elements, but you are trying to add 255 elements. 您声明数组a
的大小为10个元素,但是您尝试添加255个元素。
This is the issue. 这就是问题。 The size of a
needs to be the same of the max bound value of the main loop ( nums[0]
). 的大小a
需要是相同的主回路的最大界限值的( nums[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.