Calcifer Calcifer - 21 days ago 26
C++ Question

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.

Answer Source

You are using nums[0] as the max bound for the loop

  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].

You declared the array a to have a size of 10 elements, but you are trying to add 255 elements.

This is the issue. The size of a needs to be the same of the max bound value of the main loop (nums[0]).