![](/img/trans.png)
[英]Why does attempting to return in this function cause the program to crash in C++?
[英]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;
}
如果运行此程序,然后输入255作为数字,每个数字输入9,它将导致程序崩溃。
这是因为int a[10] = { 0 };
并尝试将其索引到第10个单元格或位置9之后。您需要修复for循环
for (int i = 0; i < nums[0]; i++)
{
cout << "Enter number " << i << endl;
cin >> a[i];
}
或更改初始化的单元格长度
为什么程序崩溃? 你只分配了10元a
。
您告诉用户"(max of 10)"
。 用户忽略此内容并输入255
。 在执行其他任何操作之前,您需要检查用户是否已听完您的警告。
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;
}
您正在使用nums[0]
作为循环的最大界限
for (int i = 0; i < nums[0]; i++)
{
cout << "Enter number " << i << endl;
cin >> a[i];
}
在您的情况下,您要进行255次循环,并且在每次迭代中,请将值添加到a[i]
。
您声明数组a
的大小为10个元素,但是您尝试添加255个元素。
这就是问题。 的大小a
需要是相同的主回路的最大界限值的( nums[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.