2-D array initialization

Ali Çehreli acehreli at yahoo.com
Sat Aug 1 22:00:43 UTC 2020


On 8/1/20 12:57 PM, Andy Balba wrote:

 > 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]  ];

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

That's surprising to me. I came from C++03 year ago but everything in D 
was much better for me. :)

I wanted to respond to your question yesterday and started typing some 
code but then I decided to ask first: Do you really need a static array? 
Otherwise, the following is a quite usable 2D array:

   ubyte[][] c = [ [5, 5, 5], [15, 15,15], [25, 25,25], [35, 35,35]  ];

However, that's quite different from a ubyte[3][4] static array because 
'c' above can be represented like the following graph in memory. (Sorry 
if this is already known to you.)

c.ptr --> | .ptr | .ptr | .ptr | .ptr |
               |      |      |      |
               .      .      |       --> | 35 | 35 | 35 | 35 |
              etc.   etc.     --> | 25 | 25 | 25 | 25 |

In other words, each element is reached through 2 dereferences in memory.

On the other hand, a static array consists of nothing but the elements 
in memory. So, a ubyte[3][4] would be the following elements in memory:

   | 5 | 5 | ... | 35 | 35 |

One big difference is that static arrays are value types, meaning that 
all elements are copied e.g. as arguments during function calls. On the 
other hand, slices are copied just as fat pointers (ptr+length pair), 
hence have reference semantics.

Here are some ways of initializing a static array. This one is the most 
natural one:

   ubyte[3][4] c = [ [5, 5, 5], [15, 15,15], [25, 25,25], [35, 35,35]  ];

Yes, that works! :) Why did you need to cast to begin with? One reason 
may be you had a value that could not fit in a ubyte so the compiler did 
not agree. (?)

This one casts a 1D array as the desired type:

   ubyte[3][4] c = *cast(ubyte[3][4]*)(cast(ubyte[])[ 5, 5, 5, 15, 15, 
15, 25, 25, 25, 35, 35, 35 ]).ptr;

The inner cast is required because 5 etc. are ints by-default.

There is std.array.staticArray as well but I haven't used it.

Ali



More information about the Digitalmars-d-learn mailing list