2-D array initialization

Andy Balba pwplus7 at gmail.com
Sat Aug 1 19:57:36 UTC 2020


On Saturday, 1 August 2020 at 00:08:33 UTC, MoonlightSentinel 
wrote:
> On Friday, 31 July 2020 at 23:42:45 UTC, Andy Balba wrote:
>> How does one initialize c in D ?
>
> ubyte[3][4] c = [ [5, 5, 5], [15, 15,15], [25, 25,25], [35, 
> 35,35]  ];
>
>> none of the statements below works
>>
>>  c = cast(ubyte) [ [5, 5, 5], [15, 15,15], [25, 25,25], [35, 
>> 35,35]  ];
>
> This is an invalid cast because it tries to coerce the entire 
> literal into an ubyte. Also  it would be an assignment instead 
> of an initialization because this is independent of c's 
> declaration.
>
>> c[0] = ubyte[3] [5, 5, 5]   ;  c[1] = ubyte[3] [15, 15,15] ;
>> c[2] = ubyte[3] [25, 25,25] ;  c[3] = ubyte[3] [35, 35,35] ;
>
> A cast is usually specified as `cast(TargetType) value` but not 
> necesseray in this example. Use this instead:
>
> c[0] = [5, 5, 5]   ;  c[1] = [15, 15,15] ;
> c[2] = [25, 25,25] ;  c[3] = [35, 35,35] ;
>
>> for (int i= 0; i<3; i++) for (int j= 0; i<4; j++) c[i][j]= 
>> cast(ubyte)(10*i +j) ;
>
> The array indices and the inner loop condition are wrong
>
> for (int i= 0; i<3; i++) for (int j= 0; j<4; j++) c[j][i]= 
> cast(ubyte)(10*i +j) ;
>
> You could also use foreach-loops, e.g.
>
> foreach (j, ref line; c)
>     foreach (i, ref cell; line)
>         cell = cast(ubyte) (10 * i + j);

@ MoonlightSentinel: sorry about the typo in for (int i= 0; i<3; 
i++) for (int j= 0; j<4; j++)

I'm a D newbie. moving over from C/C++, and I'm really finding it 
hard to adjusting to D syntax, which I find somewhat cryptic 
compared to C/C++.
After going thru a D on-line tutorial, I decided D was much 
better than C/C++, so I began by journey into D by converting one 
of my less complicated C++ apps.
I'm surprised at the enormous amount of time this D-conversion 
has taken compared to GO conversion of the very same app. 
Obviously, I need a faster way of climbing the D learning curve, 
so I would appreciate any suggestions.


More information about the Digitalmars-d-learn mailing list