I am unable to execute the below code in codeblock ide but if I declare the array globally then I can execute it.
What are the limits on array size when declared globally and when declared locally ? What is the thumb rule for declaring array size in competitive programming contest like spoj, codechef etc?
Also if the error is due to codeblock ide. Then how can I correct it ?
#include<iostream>
using namespace std;
int main()
{
int arr[999999];
return 0;
}
The reason this is disallowed is because it would add a total of 999999*sizeof(int) bytes (7.6MiB in a typical 64-bit environment) to the stack frame of main(), which is a very large amount of memory for a single stack frame.
The maximum size of a stack frame depends on your implementation and environment settings.
If you do need this memory, you should either locate it statically (using a static variable) or dynamically, depending on whether you need to have multiple calls of main() inside your program. If you settle for dynamic memory, consider using a vector instead and using std::vector<int> arr(999999);
in order to declare a vector with the initial size set to 999999.
Without the exact error (can you provide this?) it's hard to say exactly what's happen but more likely than not you are getting a stack overflow. The specific size of the stack is iplementation defined, mosst platform provide a mean of enlarging it.
The easiest and most correct solution to this problem is to use a managed standard container to hold the array like a std::vector
, this will allocate onto the freestore and manage the memory for you as well as provide a consistant interface.
#include <vector>
int main() {
std::vector<int> arr (999999);
return 0;
}
As a general rule, prefer containers to raw arrays there is very little if any overhead.
http://en.cppreference.com/w/cpp/container/vector
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With