Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring array causing error

Tags:

c++

arrays

c

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;
}
like image 864
user1543957 Avatar asked Nov 21 '12 13:11

user1543957


2 Answers

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.

like image 114
Agentlien Avatar answered Sep 19 '22 16:09

Agentlien


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.

Reference

http://en.cppreference.com/w/cpp/container/vector

like image 43
111111 Avatar answered Sep 17 '22 16:09

111111