How can I convert the following C to D.

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jan 21 16:17:54 PST 2015


On Wednesday, 21 January 2015 at 23:44:52 UTC, anon wrote:
> I have the following C code, how can I do the same in D.
>
> Info **info;
> info = new Info*[hl + 2];
>
> int r;
> for(r = 0; r < hl; r++)
> {
> 	info[r] = new Info[vl + 2];
> }
> info[r] = NULL;
>
> anon

The super-literal translation:
     Info** info;
     info = new Info*[hl + 2].ptr;
     int r;
     for(r = 0; r < hl; r++)
     {
         info[r] = new Info[vl + 2].ptr;
     }
     info[r] = null;

A little more D-ish:
     Info[][] info = new Info[][hl + 2];
     foreach(r; 0 .. hl)
     {
         info[r] = new Info[vl + 2];
     }
     assert(info[hl].length == 0); /* Relying on default 
initialization. */

D to the ultimate max:
     import std.algorithm;
     import std.range;
     auto info = iota(hl)
         .map!(i => new Info[vl + 2])
         .chain(only(Info[].init, Info[].init))
         .array;
     static assert(is(typeof(info) == Info[][]));
     assert(info.length == hl + 2);
     assert(info[hl].empty);

And if those +2 are for sentinel values, D doesn't need them 
because D arrays know their length. And it all comes down to:
     auto info = new Info[][](hl, vl);


More information about the Digitalmars-d-learn mailing list