在C++中可以将多少个值放入数组?

Ger*_*eru 2 c++ arrays double

我想读取一个从文件到数组的double值数组.我喜欢128 ^ 3的值.只要我保持128 ^ 2的值,我的程序工作得很好,但现在我得到一个"分段错误"错误,即使128 ^3≈2,100,000远远低于int的最大值.那么你实际可以将多少个值放入双打数组?

#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;
}
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 9

您正在分配堆栈上的阵列,且堆栈大小是有限的(默认,堆栈限制往往是在个位数兆字节).

你有几个选择:

  • 增加堆栈的大小(ulimit -s在Unix上);
  • 使用new; 在堆上分配数组;
  • 转向使用std::vector.