Multidimensional array

Ali Çehreli acehreli at yahoo.com
Thu Jul 4 18:30:58 PDT 2013


On 07/04/2013 03:39 PM, Oleksiy wrote:

 > 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.

It seems to be confusing to people who are used to C and C++'s 
inside-out definition. In D, it is always "type and then the square 
brackets".

 > 2. Consider this code:
 >      dchar[3][5] arr = '.';

That is an array of 5 elements where the type of each element is dchar[3].

However, that is a confusing syntax because the right-hand side is not 
the same type as the elements, which is dchar[3]. Perhaps D supports it 
for C compatibility?

It doesn't match the following. Here, the right-hand side is the same as 
the element type:

     int[2] arr2 = 42;
     assert(arr2 == [ 42, 42 ]);

But this doesn't compile:

     char[3][5] arr = [ '.', '.', '.' ];

Error: mismatched array lengths, 15 and 3

I see that as a bug but can't be sure.

 >      arr[2][] = '!';

arr[2] is the third dchar[3] of arr. When [] is applied to it all of its 
elements are set to '!'.

 >      writeln();
 >      writeln(arr);
 >
 > Result: ["...", "...", "!!!", "...", "..."]

Looks correct.

 > 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).

The book either fails to mention the term "array-wise" or does not use 
it sufficiently but Ali Çehreli is correct in that arr[] means "all of 
the elements of arr".

 > change the code:
 > -   arr[2][] = '!';
 > +   arr[][2] = '!';

arr[] is a slice to all of the elements of arr. When [2] is applied to 
it then you again get the third element.

 > Still getting the same result: ["...", "...", "!!!", "...", "..."]

Still makes sense.

 > I would expect to get: ["..!", "..!", "..!", "..!", "..!"]

Like C and C++, D does not have multi-dimensional arrays. You must do 
that yourself. One of the most straight-forward is by foreach:

import std.stdio;

void main()
{
     dchar[3][5] arr = '.';

     foreach (ref e; arr) {
         e[2] = '!';
     }

     writeln(arr);
}

["..!", "..!", "..!", "..!", "..!"]

 > since omitted index would apply the operation to all elements of the
 > first dimension of the array.

Sorry about that confusion but "a slice to all of the elements" and 
"array-wise operation" syntaxes are very similar.

   a[] alone is a slice to all of the elements of 'a'. When you use that 
syntax in an operation, then that operation is applied "array-wise":

   a[] = b[] + c[];

That is the same as

   a[i] = b[i] + c[i]

for all valid values of 'i'.

Ali



More information about the Digitalmars-d-learn mailing list