簡體   English   中英

為什么此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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM