Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

arrays

double

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;
}
like image 475
Geru Avatar asked Jan 30 '26 21:01

Geru


1 Answers

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.
like image 102
NPE Avatar answered Feb 01 '26 11:02

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!