0

I tried many different unsuccessful ways, the last of which I am describing below-

#include<iostream>
#include<fstream>

//functions here


using namespace std;

int main(){
    int n;
    long long A[300001];
    ifstream myfile("sort.in");
    myfile>>n;
    
    for(int i=0;i<n;++i){
        myfile>>A[i];
    }
    cout<<A[0];
    myfile.close();
    
    return 0;
}

This doesn't work.

Whereas, the below one works-

#include<iostream>
#include<fstream>

//functions here


using namespace std;

int main(){
    int n;
    int A[300001];
    ifstream myfile("sort.in");
    myfile>>n;
    
    for(int i=0;i<n;++i){
        myfile>>A[i];
    }
    cout<<A[0];
    myfile.close();
    
    return 0;
}

What is the problem?

The only difference is use of int instead of long long. How does that make such a big difference? By the way, by not working I mean that it is not producing any output on the screen.
levio_sa
  • 85
  • 6

2 Answers2

2

It's most likely a stack overflow problem caused by large statically defined arrays.

Instead of

long long A[300001];

use

std::vector<long long> A(300001);
R Sahu
  • 196,807
  • 13
  • 136
  • 247
0

in this case use of long long array may cause stack overflow.

try dynamicly alocated buffer:

#include<iostream>
#include<fstream>

//functions here


using namespace std;

int main(){
    int n;
    
    ifstream myfile("sort.in");
    myfile>>n;

    long long *A = new long long[n];

    for(int i=0;i<n;++i){
        myfile>>A[i];
    }
    cout<<A[0];
    myfile.close();

    delete []A;
    
    return 0;
}
Ali Askari
  • 445
  • 3
  • 7
  • Please don't use `new` in c++ (there are nearly always better techniques). In this case we should be using containers to store things like this (i.e. std::vector). – Martin York Jun 25 '20 at 18:10
  • Why do you ask not to use new? – levio_sa Jun 25 '20 at 18:16
  • 1
    @levio_sa millions of programmers have found, often to their detriment, that `new` is a lot harder to get right than it looks. As a result it's been mostly replaced (but not completely. Sometimes `new` is the only tool for the job) in modern C++ with safer options. See [Why should C++ programmers minimize use of 'new'?](https://stackoverflow.com/questions/6500313/why-should-c-programmers-minimize-use-of-new) for a longer discussion of the issues. – user4581301 Jun 25 '20 at 19:45