Wierd Error with Numbers over 100000

I am trying to make a program that simulates rolling a 10 dies multiple times. However whenever I try to use the numbers 1,000,000; 10,000,000; and 100,000,000 I get a weird error.Thanks for trying to help.

Example:

Enter the number of rolls: 1000000

Enter the desired sum: 20

--------------------------------
Process exited after 4.759 seconds with return value 3221225725
Press any key to continue . . .

The code is

#include<iostream>
#include<ctime>
#include<cstdlib>
#include<iomanip>

using namespace std;

class Dice
{

public:

int roll()
{
int sum=0;
int a[10];

for(int i=0;i<10;i++)
{
a[i]=rand()%6+1;
}
for(int i=0;i<10;i++)
{
sum+=a[i];
}
//cout<<"\t "<<sum;
return sum;
}
};
int main()
{
Dice dice;
int nrolls,desiredsum,count=0;
cout<<"Enter the number of rolls: ";
cin>>nrolls;
cout<<"\nEnter the desired sum: ";
cin>>desiredsum;
int a[nrolls];
srand(static_cast<unsigned>(time(NULL)));
for(int i=0;i<nrolls;i++)
{
a[i]=dice.roll();
if(a[i]==desiredsum)
count++;
}
cout<<"\n The desired sum "<<desiredsum<<" appears on rolling 10 dice of "<<nrolls<< " times is "<<count;






EDIT:

The random comment in the middle if the // is taken out displays the sum of every roll. More specifically it is this line of code

//cout<<"\t "<<sum;
Last edited on
1
2
3
4
5
6
int main()
{
  int nrolls;
  cin >> nrolls;
  int foo[ nrolls ];
}

Imagine that you are the compiler. Your task is to generate the binary, which on loading will have X bytes of memory for integer array foo. The foo is a statically allocated object. You know during compilation what the X is.

What is the X? The C++ standard requires you to know the X; the X must be a compile-time constant.

Alas, you cannot possibly know during compilation. Besides, statically allocated objects could be in stack memory and stack memory used to be limited compared to the heap.


What you have to do is to dynamically allocate memory for the array during runtime.

This is the easy way:
1
2
3
4
5
6
7
8
#include <vector>

int main()
{
  size_t nrolls;
  cin >> nrolls;
  std::vector<int> foo( nrolls );
}

Topic archived. No new replies allowed.