multi-dimensional dynamic arrays

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Feb 18 23:59:29 PST 2016


On Friday, February 19, 2016 06:54:51 Jay Norwood via Digitalmars-d-learn wrote:
> Strange to me that this compiles, since I would expect there to
> be some C-like limitation on the position of the unspecified
> dimension.  Is allowing this somehow useful?
>
> int[1][][1] ub;
> writeln("ub",ub);

You can have dynamic arrays of static arrays. In this case, you have a
static of dynamic arrays of static arrays. Alternatively, you could do
something like

    auto arr = new int[1][](5);

which would be a dynamic array of length 5 which holds static arrays of
length 1. Or you could do something really wonky like

    auto arr = new int[][2][](5);

which would be a dynamic array of length 5 which holds static arrays of
length 2 which hold dynamic arrays which are null. All kinds of wacky
combinations are possible. Now, are they _useful_? Well, that's another
question entirely. Personally, I wouldn't use constructs like that, because
they're too weird and too easy to screw up, but it wouldn't surprise me if
someone at some point found a use for them. Personally, I tend to dislike
even using multidimensional static arrays, because it's so easy to confuse
the dimensions. e.g.

    int[5][3] arr;
    assert(arr.length == 3);
    assert(arr[0].length == 5);

And the more complicated the array declaration, the more likely it is that
you're going to screw it up - either in how it's declared or in how it's
accessed. But the type system will let you do all kinds of crazy
combinations if you really want to.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list