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 04:12:00 PST 2016


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



More information about the Digitalmars-d-learn mailing list