I\'m somewhat new to programming in general and I\'ve run into an issue with declaring 3D and 4D arrays. I have several declarations like this at the start of my main function,
This line:
string reg_perm_mark_name[64][64][64]
declares 64*64*64 = 262144 strings on the stack. A std::string
is typically about 32 bytes so thats about 8MB. The maximum stack size is typically about 1MB.
To declare the array dynamically you could use std::vector
. Generally, multidimensional std::vector
s can be a bit cumbersome and it is often better to declare a single dimensional vector and convert to a single index when you access an element:
std::vector reg_perm_mark_name(64*64*64);
int i = 13;
int j = 27;
int k = 7;
reg_perm_mark_name[i + 64*j + 64*64*k] = "Hello world!";
But in this case you can declare a multi-dimensional std::vector
quite efficiently by using std::array
instead of std::vector
for the inner types. The use of std::array
avoids too many memory allocations as they have a fixed size. I would use typedefs or using aliases to make the declaration clearer:
using StrArray = std::array;
using StrArray2D = std::array;
std::vector reg_perm_mark_name(64);
reg_perm_mark_name[3][4][7] = "Hello world!";