-1

Why can't I declare a value like long long int v[100000000]? There's no error while compiling but when I have to input my values it simply breaks...

I have the following code:

#include <iostream>
using namespace std;
int main ()
{
    int n, i, poz, ok;
    long long int a, v[10000000], aux;
    cout << "v[0]= "; cin >> v[0];
    cout << "n= "; cin >> n;
    //cout << v[0] << " ";
    for (i=1; i<n; i++)
    {
        v[i]=((v[i-1]%31337)*(31334%31337))%31337;
        //cout << v[i] << " ";
    }
    //cout << endl;
    a=v[n-1];   
    do
    {
        ok=0;
        for (i=0; i<n-1; i++)
            if (v[i]>v[i+1])
            {
                aux=v[i];
                v[i]=v[i+1];
                v[i+1]=aux;
                ok=1;
            }
    }while (ok==1);
//  for (i=0; i<n; i++)
    //{
    //  cout << v[i] << " ";
    //}
    //cout << endl;
    for (i=0; i<n; i++)
        if (v[i]==a)
            poz=i+1;
    cout << poz;
    return 0;
}

And I have to input the values: [11863, 1661427]. Any ideas what should I do to input those values?

KeykoYume
  • 33
  • 1
  • 3
  • 8

2 Answers2

4

The C++ Standard has an Appendix dedicated to "Implementation Quantities", explained as

Because computers are finite, C++ implementations are inevitably limited in the size of the programs they can successfully process.

You've exceeded your implementation's limit on the total size of variables of automatic storage duration. (Typically knows as "stack size").

You might try using dynamic allocation instead:

std::vector<long long int> v(10000000);

Dynamic allocations are constrained also, but the limit typically depends on the size of the largest fragment of address space, which is usually far far larger than the stack size.

Static storage duration as Vlad suggests also changes which limit applies, but there tend to be severe drawbacks to large objects of static storage duration (such as the executable file being several gigabytes on disk and taking minutes to load).

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
0

This array is allocated in the stack the memory of which is usually very limited. Use instead

static long long v[10000000];

Or it would be better to use standard container std::vector<long long>. Moreover as it is seen from your code the actual size of the array depends on the number entered by the user. So it would be indeed better to use std::vector<long long>

For example

cout << "n= "; cin >> n;
std::vector<long long> v( n );

or

cout << "n= "; cin >> n;
std::vector<long long> v;
v.reserve( n );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335