www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Multidimensional array access

reply somebody <some.body mail.com> writes:
I though D should have syntax similarities with C, but recently 
I've found that array indexing in D is different. Suppose we have 
a code:

import std.stdio;

void main ()
{
     wstring[6][2] strings;
     strings[2][0] = "test";
}


It fails to compile because of error:

"./main.d(6): Error: array index 2 is out of bounds strings[0 .. 
2]"

Why? There should be 6 rows and 2 columns, but it seems that it's 
the opposite. Am I misunderstood something or is it a bug?
Dec 20 2016
next sibling parent Madaz Hill <mhmhmh mhmh.mh> writes:
On Tuesday, 20 December 2016 at 19:59:41 UTC, somebody wrote:
 I though D should have syntax similarities with C, but recently 
 I've found that array indexing in D is different. Suppose we 
 have a code:

 import std.stdio;

 void main ()
 {
     wstring[6][2] strings;
     strings[2][0] = "test";
 }


 It fails to compile because of error:

 "./main.d(6): Error: array index 2 is out of bounds strings[0 
 .. 2]"

 Why? There should be 6 rows and 2 columns, but it seems that 
 it's the opposite. Am I misunderstood something or is it a bug?
Your code is like this: alias S = wstring[6]; S[2] strings; strings[2] = "test"; You see your error now ?
Dec 20 2016
prev sibling next sibling parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 12/20/2016 11:59 AM, somebody wrote:
 I though D should have syntax similarities with C, but recently I've
 found that array indexing in D is different. Suppose we have a code:

 import std.stdio;

 void main ()
 {
     wstring[6][2] strings;
     strings[2][0] = "test";
 }


 It fails to compile because of error:

 "./main.d(6): Error: array index 2 is out of bounds strings[0 .. 2]"

 Why? There should be 6 rows and 2 columns, but it seems that it's the
 opposite. Am I misunderstood something or is it a bug?
Yes, opposite. C's array declaration mimics the way arrays are used in code: first row, then column. In D, array declarations are always "type followed by square brackets"; int[N] arr; Array of arrays follow the same consistent definition: first type, then the square brackets. So if we need an array of 6 elements where the type of elements is int[2], then we follow that description (space added for emphasis): int[2] [6] arr; Ali
Dec 20 2016
prev sibling parent somebody <some.body mail.com> writes:
Thanks for the explanation
Dec 20 2016