How to initialize this multidimensional array?

I have a giant 3-dimensional array that represents my world. It is too large to initialize statically:

alias Cell[128][128][128] World; // <-- The compiler points to this line Error: index 128 overflow for static array 

I tried using World* world , but it still throws errors with overflow above. So now I have this ugly mess:

 alias Cell[][][] World; // ... private World world; // ... world.length = WORLD_XDIM; for (uint x = 0; x < world.length; ++x) { world[x].length = WORLD_YDIM; for (uint y = 0; y < world[x].length; ++y) { world[x][y].length = WORLD_ZDIM; } } 

It works, but it makes me cry a little inside. Is there a way to pass the result of a calloc to a three-dimensional array? I did this with slicing regular arrays, but the three-dimensional thing scares me.

+6
source share
1 answer

If you want to declare a jagged array (i.e. where each submatrix can have a different length), you need to use a loop like you do, but this is not necessary for homogeneous arrays. Here's how you initialize a multidimensional array that is not jagged:

 auto arr = new Cell[][][](128, 128, 128); 

When you put numbers between brackets, you make them a dynamic array of static arrays. Thus,

 auto arr = new Cell[128][128][128]; 

declares a dynamic array of static arrays of 128 lengths of static arrays of length 128. I suppose it would be useful if you really needed to do this (which I never had), but it definitely pushes newbies on a regular basis.

Personally, to completely eliminate such problems, I simply did not put numbers between the brackets, even when I declared one dimensional array:

 auto arr = new Cell[](128); 

I find the fact that putting a number between brackets in the first dimension is considered a dynamic array, while placing numbers at any subsequent levels is considered a static array, to be a poor design choice, and I don’t know why it is, but as it is. I can understand that I want to be able to create dynamic arrays of static arrays, but it would be much more sequential to either prohibit new Cell[128] or force it to return Cell[128]* rather than Cell[] length 128, but unfortunately that is not how it works.

+9
source

Source: https://habr.com/ru/post/915320/


All Articles