Trying to understand multidimensional arrays in D

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jan 29 23:33:34 PST 2017


On 01/25/2017 05:47 PM, Profile Anaysis wrote:

 > a 4x4 matrix and have a history of it. Just
 > n 4x4 matrices but each matrix is a fixed size but there can be an
 > arbitrary(dynamic) number.

I don't think using aliases is recommended yet. It can simplify things a 
lot:

import std.stdio;

alias Row = int[4];
alias Matrix = Row[4];
alias History = Matrix[];

Row makeRow(int value) {
     Row row;
     row = value;    // Special array syntax; all elements are now 'value'
     return row;
}

Matrix makeMatrix() {
     Matrix matrix;
     foreach (int i, ref row; matrix) {
         row = makeRow(i + 1);
     }
     return matrix;
}

void main() {
     History history;
     foreach (i; 0..3) {
         history ~= makeMatrix();
     }
     writeln(history);
}

As others have said, D's array definition is natural because unlike C's 
inside-out (or is that outside-in?) syntax, it follows from the alias 
syntax. Replacing History inside main with Matrix[], etc.:

     History history;    // is the same as:
     Matrix[] history;   // is the same as:
     Row[4][] history;   // is the same as:
     int[4][4][] history;

Ali



More information about the Digitalmars-d-learn mailing list