这个C++程序为什么会导致系统崩溃?

问题描述:

#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个,它会导致它崩溃。这个C++程序为什么会导致系统崩溃?

+2

“它导致它崩溃”中的第二个“it”是什么?整个电脑的操作系统,或只是你的程序? –

+0

如果您正在学习C++,首先需要了解标准库中提供了哪些工具。当存储类似数组的数据时,['std:vector'](http://en.cppreference.com/w/cpp/container/vector)是一个很好的开始。使用那些优先于固定长度的C风格的阵列,就像你在这里一样。 – tadman

您正在使用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])相同。

为什么你的程序崩溃?您只为a分配了10个元素。


您告诉用户"(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; 
} 

其因int a[10] = { 0 };并尝试索引它过去的第10个小区或位置9 你需要修复您的for循环

for (int i = 0; i < nums[0]; i++) 
    { 
    cout << "Enter number " << i << endl; 
    cin >> a[i]; 
    } 

或更改intialization

你的电池的长度