setting array dimensions at runtime

Nekuromento max.klyga at gmail.com
Sun Dec 5 10:52:02 PST 2010


On 2010-12-05 19:41:50 +0200, user at domain.invalid said:

> Hello,
> 
> I've been wondering what the easiest way is to set
> the dimension of an array during runtime.
> 
> You can't write
> 
>     byte[][] a = new byte[size][size];
> 
> because the compiler will give an error. The only
> thing I've been able to think of is
> 
>     byte[][] a;
>     a.length = size;
>     for (int i; i < size; i++) {
>          a[i].length = size;
>     }
> 
> But it's slower (and less convenient) than
> writing
> 
>     byte[][] a = new byte[9][9];

The syntax might seem a bit misleading, but you can create 
multidimentional arrays like this:
    int[][] foo = new int[][](5,10);
    foo[4][9] = 31337;

this also works for single-dimention arrays (e.g int[] foo = new int[](size);)



More information about the Digitalmars-d-learn mailing list