Geru
Geru

Reputation: 654

How many values can be put into an Array in C++?

I wanted to read an array of double values from a file to an array. I have like 128^3 values. My program worked just fine as long as I stayed at 128^2 values, but now I get an "segmentation fault" error, even though 128^3 ≈ 2,100,000 is by far below the maximum of int. So how many values can you actually put into an array of doubles?

#include <iostream>
#include <fstream>
int LENGTH = 128;

int main(int argc, const char * argv[]) {
    // insert code here...
    const int arrLength = LENGTH*LENGTH*LENGTH;
    std::string filename = "density.dat";
    std::cout << "opening file" << std::endl;
    std::ifstream infile(filename.c_str());
    std::cout << "creating array with length " << arrLength << std::endl;
    double* densdata[arrLength];


    std::cout << "Array created"<< std::endl;
    for(int i=0; i < arrLength; ++i){
        double a;

        infile >> a;
        densdata[i] = &a;
        std::cout << "read value: " << a  << " at line " << (i+1) << std::endl;
    }
    return 0;
}

Upvotes: 2

Views: 1822

Answers (1)

NPE
NPE

Reputation: 500357

You are allocating the array on the stack, and stack size is limited (by default, stack limit tends to be in single-digit megabytes).

You have several options:

  • increase the size of the stack (ulimit -s on Unix);
  • allocate the array on the heap using new;
  • move to using std::vector.

Upvotes: 9

Related Questions