Multidimensional array

bearophile bearophileHUGS at lycos.com
Thu Jul 4 16:17:36 PDT 2013


Oleksiy:

> 1. What is the rationale behind "prefix declaration" of an 
> array? Using right-to-left order to declare an array and 
> left-to-right order to access elements seems confusing.

I think the way Go language declares arrays and pointers is a bit 
better. But for the rationale of this part of D design others 
should answer you.


> 2. Consider this code:
>     dchar[3][5] arr = '.';
>     arr[2][] = '!';
>     writeln();
>     writeln(arr);
>
> Result: ["...", "...", "!!!", "...", "..."]
> Which is expected. According to Ali Çehreli's tutorial, 
> omitting the index of an array will result in operation being 
> applied to the whole array (in this case element of another 
> array).
>
> change the code:
> -   arr[2][] = '!';
> +   arr[][2] = '!';
>
> Still getting the same result: ["...", "...", "!!!", "...", 
> "..."]
>
> I would expect to get: ["..!", "..!", "..!", "..!", "..!"]
> since omitted index would apply the operation to all elements 
> of the first dimension of the array.
>
> What am I missing?

Ali Çehreli's tutorial is not correct, or you have not understood 
it correctly.

In D there are dynamic arrays and fixed sized arrays.

When you write:

dchar[3][5] arr;

You are allocating a fixed sized matrix in place (often on the 
stack or you are defining one inside another class instance or 
struct instance).

The array-wise (vector operation) is done only one the last 
array, so this works:

arr[2][] = '!';

But:

arr[][2] = '!';

is a totally different thing. You are slicing the rows, and then 
you are assigning something to all the items of the third row.

Always compile your D code with "-wi", it gives you a warning 
here, helping you avoid your mistake. I am asking all the time to 
produce warnings on default, but Walkter&Andrei don't even answer 
"No" to my request.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list