Assigning to slice of array

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Mar 1 21:34:41 UTC 2018


On Thursday, March 01, 2018 21:16:54 Jamie via Digitalmars-d-learn wrote:
> I'm trying to understand arrays and have read a lot of the
> information about them on this forum. I think I understand that
> they are set-up like Type[], so that int[][] actually means an
> array of int[].
>
> I create an array as per the following:
>      auto arr = new int[3][2][1];
> which produces:

Don't put the indices within the brackets. What you want is

auto arr = new int[][][](3, 2, 1);

With a new expression, unless you only have one dimension, you end up with
dynamic arrays of static arrays. e.g. if you use what I wrote there with

pragma(msg, typeof(arr).stringof);

it prints

int[][][]

whereas with what you wrote, you get

int[3][2][]

which is a dynamic array of a static array of length 2 of static arrays of
int of length 3 rather than a dynamic array of a dynamic array of a dynamic
array of ints. Unfortunately,

auto arr = new int[5];

and

auto arr = new int[](5);

are equivalent, so dealing with just single dimension arrays does not
prepare you properly for dealing with multi-dimensional arrays. Arguably, it
would have been better to just force using the parens, though that would
make the most common case more verbose, so it's debatable.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list