Declare large array on Stack

后端 未结 4 1047
我寻月下人不归
我寻月下人不归 2020-12-03 15:45

I am using Dev C++ to write a simulation program. For it, I need to declare a single dimensional array with the data type double. It contains 4200000

4条回答
  •  温柔的废话
    2020-12-03 16:08

    No there is no(we'll say "reasonable") way to declare this array on the stack. You can however declare the pointer on the stack, and set aside a bit of memory on the heap.

    double *n = new double[4200000];
    

    accessing n[234] of this, should be no quicker than accessing n[234] of an array that you declared like this:

    double n[500];
    

    Or even better, you could use vectors

    std::vector someElements(4200000);
    someElements[234];//Is equally fast as our n[234] from other examples, if you optimize (-O3) and the difference on small programs is negligible if you don't(+5%)
    

    Which if you optimize with -O3, is just as fast as an array, and much safer. As with the

    double *n = new double[4200000]; 
    

    solution you will leak memory unless you do this:

    delete[] n;
    

    And with exceptions and various things, this is a very unsafe way of doing things.

提交回复
热议问题