Strange behavior of array

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Oct 16 00:25:05 PDT 2015


On Friday, October 16, 2015 04:39:57 Mike Parker via Digitalmars-d-learn wrote:
> On Friday, 16 October 2015 at 03:01:12 UTC, VlasovRoman wrote:
>
> > Oh, thank you. Some strange solution.
>
> D doesn't have multidimensional built-in arrays, but rectangular
> arrays. Think of it this way:
>
> int[3] a1;
>
> a1 is a static array of 3 ints. Indexing it returns an int. We
> can think of it like this:
>
> (int)[3]
>
> On the same lines:
>
> int[3][4] a2;
>
> a2 is a static array of 4 static arrays of 3 ints. In other words:
>
> (int[3])[4].
>
> Therefore, int[0] returns the first int[3], int[1] the second,
> and so on.
>
> int[0][1] returns the second element of the first int[3].
>
> Rikki's solution to your problem was to reverse the indexes when
> reading the array. But if you want to index it just as you would
> in C or C++, you should reverse the indexes in the declaration.
> Where you declare int[rows][columns] in C, you would declare
> int[columns][rows] in D, then reading from them is identical.

That does work currently, but there's talk off and on about deprecating the
C syntax, so that may happen at some point, just like the C function pointer
syntax was deprecated. Regardless, using the C array declaration syntax is
generally discouraged - though the fact that the D syntax for static arrays
is basically the reverse of what folks expect (much as it makes perfect
sense from the compiler's point of view with how types are put together)
definitely does make things confusing.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list