# Declare arrangement of 0 = N = 2000000

3

The program crashed

I need to declare an array of 2000000 elements, how do you declare it?

Problem

Write a program that given the list of N numbers determine in what position the element a0 (the first one on the list) remains after it is sorted.

Entry

Your program should read the following information from the keyboard: In the first line the whole number N, the number of numbers in the list. In the second line the N numbers of the list separated each one by a space.

Exit

Your program must write on the screen a single integer that represents the final position of element a0a0 in the sorted list.

Restrictions: 1

asked by Esteban Vera 23.05.2017 в 02:47
source

3

I need to declare an array of 2000000 elements, how do you declare it?

### Problem.

From what I see in your code, you are declaring the array on the stack:

``````int main(){
// ...
// ...
int a,aux,i,j,e;
// ...
int v[2000000];
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// todas las variables automaticas se crean en la pila
``````

This type of memory is intended to store small data 1 but when you order two million integers you are requesting eight million bytes (about 7.6Mb) which is much more than the stack usually can store.

### Solution.

Use dynamic memory:

``````int main(){
// ...
// ...
int a,aux,i,j,e;
// ...
int *v = new int[2000000]{}; // Memoria dinámica
``````

Do not forget to free the memory when you finish:

``````delete[] v;
``````

### Improvement.

Use the class `std::vector` :

``````int main(){
// ...
// ...
int a,aux,i,j,e;
// ...
std::array<int, 2000000> v{{}}; // Dos millones de enteros con valor 0.
``````

1 The size of the stack depends on the implementation of the compiler, being able to vary between compilers. For example, my version of Visual Studio uses a 1Mb stack that is usually enough to accommodate any variable required by a function.

1
``````int v[2000000];
``````

With that innocent line you are creating in the application stack an array of 8,000,000 bytes or, which is the same, 7.62 MB. The stack of a program usually has a limited size and is usually not too large ... in fact the one that comes by default with VisualStudio I remember that round the MegaByte.

What is happening is that this instruction fills the stack of the program and overflows it and that causes the application to die suddenly (the Operating System kills the application to avoid corrupting memory of other applications).

The solution is to use dynamic memory:

``````int *v = new int[a];

// ...

delete[] v;
``````