Possible Duplicate:
Why does this code crash?
Please tell me whats wrong with the following code???Why is it crashing???
I cant store the collatz values in the array however if I want to print them individually it works perfectly.
#include <iostream>
long collatz(long);
int main()
{
using namespace std;
long i=3,t[1000000],p;
t[0]=0,t[1]=0,t[2]=0;
for(i=3; i<1000000; i++)
{
p=collatz(i);
t[i]=p;
}
cin.clear();
cin.get();
}
long collatz(long n)
{
long count=0;
do {
if (n%2==0)
{
n=n/2;
count+=1;
}
else
{
n=((3*n)+1);
count+=1;
}
} while(n!=1);
return count;
}
It’s likely that stack allocation for:
long t[1000000];fails. So when you actually write into the array, it invokes undefined behaviour.Allocate dynamically or use standard containers.