Doubt - Static multidimension arrays

tsbockman via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jan 19 12:39:37 PST 2016


On Tuesday, 19 January 2016 at 19:14:30 UTC, alb wrote:
> So guys: Ali, Mike Parker and tsbockman thanks for all your 
> explanation, in fact looking now I and after making some tests 
> I really got it.
>
> So:
>    int[2]    a1; // Array of 2 elements of type int
>
>    int[2][5] a2; // Array of 2 elements of type int divided in 
> 5 rows
>
>    writeln(a2[0]); // = accessing row 0 = [0,0]
>    writeln(a2[4]); // = accessing row 4 = [0,0]

One other thing you may want to keep in mind when working on this 
kind of thing - when you loop over a multi-dimensional array, the 
order matters.

For large arrays, this:

     int[c_max][r_max] arr;

     foreach(r; 0 .. r_max)
     {
         foreach(c; 0 .. c_max)
         {
             // do something with arr[r][c] here
         }
     }

Can be *much* faster than this:

     int[c_max][r_max] arr;

     foreach(c; 0 .. c_max)
     {
         foreach(r; 0 .. r_max)
         {
             // do something with arr[r][c] here
         }
     }

The reason is that the first version access the elements in the 
order that they are actually stored in memory, whereas the second 
forces the CPU to jump between rows for each element.

> If that in mind, now it all makes sense for me, and of course 
> it's consistent as well. Sorry to bother about this, but I 
> think this will help other newcomers.
>
> Thanks again for help/tips which helped turn my mindset.
>
> Albert.

You're welcome.

And yes, it can definitely be confusing. I understand why the 
array syntax in D is the way it is, but that still doesn't always 
save me from mixing things up once in a while anyway.


More information about the Digitalmars-d-learn mailing list