On Tuesday, 29 August 2017 at 03:16:13 UTC, Johnson Jones wrote:
T[] arr

and is a linear sequential memory array of T's with an unbound length and is effectively the same as T*(although D treats them differently?)?


It is a T* AND a size variable bundled together.

We can fix the length by adding a upper bound:

T[N] arr;

That's actually an entirely different type. This is now a block of static memory instead of a pointer+length combo.

and this is equivalent to

auto arr = cast(T[])malloc(T.sizeof*N)[0..N];

No, it isn't. The static array T[N] has no such allocation, it is all in-place.

Now, when it comes to multidimensional arrays:

T[][] arr;

That's an array of arrays. A pointer+length combo to a bunch of other pointer+length combos.

or, lets used a fixed array so we can be clear;

T[N][M]

which means we have M sequential chunks of memory where each chunk is a T[N] array.

That's correct though, with the caveat that there's no padding between the inner arrays; the T[N][M] is a single block of memory with size N * M * T.sizeof.

Similary, to access the element at the nth element in the mth chunk, we do

t[n][m] because, again, this conforms with out we think of single arrays.

I've never understood how anyone thought that made any sense. I have always thought C was backwards and illogical for that nonsense and even after many years of using C, I'd still often get it "backwards".

D doing the sane thing and having consistent order is one of the things I like about the language.



T[N][M]

one must access the element as

t[m][n]!

The accessors are backwards!

What is t[m]? It gets the m'th element of t, right? Well, since t is an array of N items, it makes perfect logical sense that t[m] is is of type T[N].

Just like how T[N]* is a pointer to a T[N] (which is an array of T), or if it were a function, t(n) would be its return value. D always follows this simple recursive rule.



Now, what's important about all this is the built-in things are arrays of arrays rather than multi-dimensional arrays. D also supports multi-dimensional arrays, which are indexed: T[x, y].

The actual type of them is not built into the language though - it needs to be defined as a library type. I'm not sure it ever got into phobos but it is available here: https://github.com/libmir/mir-algorithm

Or you can write your own pretty quickly with a static array + the opIndex overload.

Reply via email to