How to set array length for multidimensional static arrays

Daniel Kozak via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Feb 1 04:22:23 PST 2016


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



More information about the Digitalmars-d-learn mailing list