Trying to understand multidimensional arrays in D

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jan 26 00:41:24 PST 2017


On Thursday, 26 January 2017 at 05:50:03 UTC, Profile Anaysis 
wrote:

> It is inconsistent with dynamic arrays and mixing them creates 
> a mess in the order of indices.
>
> I best someone was asleep at the wheel when programming the 
> code for static arrays. (probably someone different than who 
> programmed the dynamic arrays)
>
> This is a bug IMO.(unfortunately one that can't be fixed ;/)

No, there's no inconsistence and there's no bug. Shorten things 
down a bit:

```
auto x = new int[][](3,4);
auto y = new int[3][](4);
writefln("%s, %s", x[0].length, y[0].length);
```
This will print 4, 3. Why?

auto a = int[](4);

In this case, a is an array of int. The allocation makes space 
for 4 values of type int.

auto b = int[][](4);

Here, b is an array of int[]. The allocation makes space for 
values of type int[].

The following are the equivalent declarations for static arrays:

auto c = int[4];
auto d = int[][4];

In other words  int[][4] is the static equivalent of new 
int[][](4).

Following from that:

auto e = new int[][](4, 3);

This creates an array of 4 values of type int[], each of which is 
an array that holds 3 values of type int. The static equivalent:

auto f = int[3][4];

So based on that, you should be able to see that the problem is 
not in the implementation of static arrays in D, but a mismatch 
in your declarations.

auto x = new int[][][][](1,2,3,4);
auto y = new int[1][2][][](3,4); // Does not match declaration of 
x

To get what you want, change the declaration of x:

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


More information about the Digitalmars-d-learn mailing list