0

I want to execute large computational program in 3 and 2 dimension with size of array[40000][40000] or more ,this code can explain my problem a bit,I comment vector because it have same problem when I run it it goes to lib of vector, how to increase memory of compiler or delete(clean) some part of it when program running?

#include<iostream>
#include<cstdlib>
#include<vector>
using namespace std;
int main(){
    float array[40000][40000];
    //vector< vector<double> > array(1000,1000);    
    cout<<"bingo"<<endl;
    return 0;
}
Pek
  • 166
  • 1
  • 15
  • 3
    Local variables, including arrays, are usually placed on the stack. The stack is a limited resource, on Windows using the Visual Studio compiler the default stack size is a single megabyte. Your array (assuming four-byte `float`) is almost 6 **GIGA**byte (40000 * 40000 * 4). The solution is to use vectors, so why have you commented it out? Perhaps all you need is [a good `std::vector` reference](http://en.cppreference.com/w/cpp/container/vector)? Especially about [its constructor](http://en.cppreference.com/w/cpp/container/vector/vector)? Assuming you have enough memory that is. – Some programmer dude Dec 04 '17 at 15:12
  • 3
    Please, could you explain your problem (other then too big an array) a *bit* more? – Bob__ Dec 04 '17 at 15:14
  • 1
    "because it have same problem" no, it's a **different** problem. – n. m. could be an AI Dec 04 '17 at 15:20
  • how to increase memory of compiler ? – mreza kardgar Dec 04 '17 at 15:21
  • You might consider using a memory mapped file. Or, if your data is sparse, a map container. – wally Dec 04 '17 at 15:26

1 Answers1

3

A slightly better option than vector (and far better than vector-of-vector1), which like vector, uses dynamic allocation for the contents (and therefore doesn't overflow the stack), but doesn't invite resizing:

std::unique_ptr<float[][40000]> array{ new float[40000][40000] };

Conveniently, float[40000][40000] still appears, making it fairly obvious what is going on here even to a programmer unfamiliar with incomplete array types.


1 vector<vector<T> > is very bad, since it would have many different allocations, which all have to be separately initialized, and the resulting storage would be discontiguous. Slightly better is a combination of vector<T> with vector<T*>, with the latter storing pointers created one row apart into a single large buffer managed by the former.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • Wouldn't it be `auto big_array = std::make_unique(40000);` even [better](https://stackoverflow.com/a/22571331/4944425)? – Bob__ Dec 04 '17 at 21:39
  • @Bob__: `make_unique` has advantages when there are multiple allocations in a single full-expression. In this example there are no advantages to `make_unique`. And I would consider that syntax to be less clear to readers at OP's skill level. – Ben Voigt Dec 04 '17 at 21:47