Reputation: 57
I am new to programming.I am using Dev C++ on Windows 7(x86).I am trying to run the following program.I don't think that there is a logical error causing the program to crash.The program is running on an online jugde(Codeforces). What should I do to successfully execute the program?
My solution:
#include<iostream>
using namespace std;
int main()
{
int n,i,j;
long long a[100000],b[100000],sort[200000],temp;
char aresult[100000],bresult[100000];
char*sortpoint[200000];
cin>>n;
for(i=0;i<n;i++)
{
cin>>a[i]>>b[i];
aresult[i]='0';
bresult[i]='0';
}
for(i=0;i<(n/2);i++)
{
aresult[i]='1';
bresult[i]='1';
}
i=0;
j=n+i;
for(i=0;i<n;i++)
{
sort[i]=a[i];
sort[j]=b[i];
sortpoint[i]=&aresult[i];
sortpoint[j]=&bresult[i];
j++;
}
for(i=0;i<(2*n);i++)
{
for(j=0;j<(2*n)-i-1;j++)
{
if(sort[j]>sort[j+1])
{
temp=sort[j];
sort[j]=sort[j+1];
sort[j+1]=temp;
}
}
}
for(i=0;i<n;i++)
{
*sortpoint[i]='1';
}
cout<<aresult<<endl<<bresult;
}
Upvotes: 0
Views: 1264
Reputation: 323
You are experiencing a state known as stack overflow because of which the program is crashing. Mainly because there is static allocation of large array elements. Since in your program n is a value that is a variable and which is required in the loops testing condition I recommend you to dynamically allocate memory. This will save a lot of memory that is getting wasted. To do that you can use the new operator. If you want a better way to organize the data you may use a linked list, even. But it will increase the complexity of your program.
Upvotes: 0
Reputation: 62542
You're allocating too much on the stack. The default stack size for a thread is 1MB, unless it's been explicitly altered, and your arrays exceed that.
Instead, move the data onto the heap. For example:L
long long *a=new long long[100000];
Where you're only restricted my the available virtual memory of your process, which will be 2GB for a 32bit Windows application.
Upvotes: 1