How to set array length for multidimensional static arrays

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Feb 1 07:01:08 PST 2016


On Monday, February 01, 2016 13:22:23 Daniel Kozak via Digitalmars-d-learn wrote:
> V Mon, 01 Feb 2016 12:19:10 +0000
> Namal via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com>
> napsáno:
>
> > On Monday, 1 February 2016 at 12:12:00 UTC, Jonathan M Davis
> > wrote:
> > > On Monday, February 01, 2016 11:15:40 Namal via
> > > Digitalmars-d-learn wrote:
> > >> Sorry guys that I didn't express myself well. I also mixed
> > >> some stuff up. What I wanted to ask is this, in c++ this is
> > >> valid
> > >>
> > >>   int x = 3;
> > >>   int y = 10;
> > >>   int arr [x][y];
> > >>
> > >> x,y are known at the compile time and arr is a static array. I
> > >> can't do that in D so what is the best way to declare an array
> > >> of that size?
> > >
> > > If x and y are known at compile time, then you can declare a
> > > static array using them for dimensions. e.g.
> > >
> > >     enum x = 3;
> > >     enum y = 10;
> > >     int[y][x] arr;
> > >
> > > But x and y must be something that it is evaluated by the
> > > compiler at compile time - e.g. an enum or a static variable. A
> > > local variable that just so happens to be directly initialized
> > > (like in your example) won't work.
> > >
> > > If x and y are _not_ known at compile time, then you can't use
> > > the to declare a static array. You'll have to use a dynamic
> > > array. e.g.
> > >
> > >     auto arr = new int[][](x, y);
> > >
> > > - Jonathan M Davis
> >
> > Thanks alot, I didn't know that way with new.
>
> you can use this too:
> auto arr = new int[y][x];

True, but that's not the same thing. It creates a dynamic array of static
arrays instead of a static array of dynamic arrays. e.g.

    auto a = new int[][](5, 10);
    auto b = new int[5][10];
    auto c = new int[5][](10);
    writeln(typeof(a).stringof);
    writeln(typeof(b).stringof);
    writeln(typeof(c).stringof);

prints

    int[][]
    int[5][]
    int[5][]

And in the cases where the inner element is a static array, its length has
to be known compile time, whereas the lengths of the dynamic arrays don't.

On a side note, I really wish that putting the size inside of the brackets
was illegal for dynamic arrays to make what's going on clearer, but instead,
the outer layer can go either in the brackets or in the parens, whereas
where the other layers go changes them between dynamic arrays and static
arrays.

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list