Fixed size multidimensional array at runtime

Jonathan M Davis jmdavisProg at gmx.com
Sat Jun 30 11:31:53 PDT 2012


On Saturday, June 30, 2012 20:21:57 Vidar Wahlberg wrote:
> I know multidimensional arrays has been brought up many times,
> although I was not able to find a clear answer to my question. My
> knowledge of what's going on behind the curtains is somewhat
> lacking, please correct me if my assumptions are incorrect.
> 
> Creating a dynamic multidimensional array can be easily achieved
> with for example "auto matrix = new int[][](4, 2);", although if
> I've understood it correct this would create a "jagged" array (as
> explained on page 112 in TDPL) which may cause efficiency issues
> due to two indirections as opposed to only one indirection which
> you would have in a "rectangular" array (as explained at
> http://dlang.org/arrays.html). If you at compile time know the
> dimensions of the array you could write "int[2][4] matrix;", and
> I've understood this as creating a "rectangular" array.
> 
> In my case I don't know the dimensions at compile time, but I'm
> still interested in creating a multidimensional array with only
> one indirection (i.e. allocated contiguously in memory) at
> runtime, where I'm not going to modify the size of the array. Is
> this impossible* in D?
> *I know I could create a one-dimensional array and
> programmatically convert from multiple dimensions to one
> dimension, yet this is not as satisfactory as a "true"
> multidimensional array.
> 
> Obviously it's the efficiency I worry about, I would much
> appreciate if someone could shed light upon this.

In D, static arrays are always fixed in size, and that size must be known at 
compile time, whereas dynamic arrays are never fixed in size (unless they're 
immutable), and the size doesn't need to be known at compile time. There is no 
way to have a static array whose size isn't known at compile time, which is 
what you'd need for what you're trying to do.

I believe that the only way to do it would be to create a struct which wrapped 
a single dimensional, dynamic array, and then overloaded opIndex appropriately 
so that you could index it as it were multi-dimensional, which aside from the 
fact that the array _could_ be resized (though presumably, you wouldn't make 
that possible through your struct's API), that's exactly what a rectangular 
array implementation would be doing anyway.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list