setting array dimensions at runtime

Jonathan M Davis jmdavisProg at gmx.com
Sun Dec 5 14:31:51 PST 2010


On Sunday 05 December 2010 09:41:50 user at domain.invalid wrote:
> 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];

auto a = new byte[][](9, 9);

is the way to do it. Otherwise, I believe that you're trying to create a dynamic 
array of static arrays or somesuch. I'm not sure exactly what the problem is. 
However, if you just always put the array size in the parens rather than in the 
brackets when creating an array, then it works correctly. Setting the length in 
a loop like that (or creating inner arrays with new) is best when you want the 
inner arrays to be of different length. But when you want them to be the same 
length, then putting the sizes in the parens in the correct way to go.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list