![](/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.