Does D support dynamically allocated multi-dimensional arrays?
Jonathan M Davis
jmdavisprog at gmail.com
Sun Aug 15 19:30:57 PDT 2010
On Sunday 15 August 2010 19:20:12 Seth Hoenig wrote:
> What I really want is something like this:
>
> auto s = args[1];
> auto t = args[2];
> auto d = new int[s.length][t.length];
>
> but the compiler complains with the error: Error: Integer constant
> expression expected instead of s.length
>
> So then I try to fudge it with something like:
>
> auto d = new int[][t.length];
> d.length = s.length;
>
> But then accessing elements of d throws an exception:
> core.exception.RangeError at Lev(7): Range violation
>
> Soo.. how am I supposed to make a matrix when I don't know the dimensions
> at compile time?
I generally declare dynamically allocated arrays like so:
auto arr = args[](thesize);
auto multiArr = args[][](thesize, theothersize);
So, in your case, you'd use:
auto s = args[1];
auto t args[2];
auto d = new int[][](s.length, t.length);
IIRC, the problem with putting the numbers in the brackets is that it starts
trying to do stuff like declare dynamic arrays of static arrays or somesuch. I
gave up on putting the sizes in the brackets with dynamic arrays ages ago, so I
don't remember the exact details. It just seems simpler to put it in the parens
and not worry about it, as silly as it seems. You still access them normally
with the indices in the brackets, but there are definitely issues with declaring
dynamic arrays and putting the length of the arrays in the brackets.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list