Trying to understand multidimensional arrays in D
Ivan Kazmenko via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Jan 25 18:29:07 PST 2017
On Thursday, 26 January 2017 at 01:47:53 UTC, Profile Anaysis
wrote:
> does this mean that have
>
> int[][4][4] matrix_history;
>
> backwards?
>
> int[4][4][] matrix_history;
>
> this creates even a more set of problems.
In short, you are right, `int[4][4][]` is a dynamic array of
`int[4][4]`. In turn, `int[4][4]` is a static length-4 array of
`int[4]`, and that is a static length-4 array of `int`. It's
quite logical once you learn how to read it: if T is a type, then
T[] is a dynamic array of that type, and T[4] is a static
length-4 array of that type.
So, if I have `int[2][5][7] a;` somewhere, the very last element
is `a[6][4][1]`. If you are inclined to think in terms of this
difference, the simple rule of thumb would be that the order of
dimensions in the declaration is reversed.
Also, note that if you want to have, for example, a dynamic array
of 5 dynamic arrays of the same length 7 (modeling a C
rectangular array, or a D static array, but with possibility to
change the length of each row, as well as the number of rows),
you would go with
`auto a = new int [] [] (5, 7);` (initialization)
The static array of 5 static arrays of length 7 is still
`int [7] [5] a;` (type declaration)
So the reverse only happens in type declarations.
(On the contrary, declarations in C or C++ looks rather
unintuitive from this perspective: `T a[4][5][6]` is means that
`a` is an array of 4 arrays of 5 arrays of 6 arrays of `T`. Note
how we have to read left-to-right but then wrap around the string
to get the meaning.)
Additionally, reading about various kinds of arrays in D might
help:
https://dlang.org/spec/arrays.html
And more in-depth material about array slicing:
http://dlang.org/d-array-article.html
Ivan Kazmenko.
More information about the Digitalmars-d-learn
mailing list