why no implicit convertion?
Jonathan M Davis
jmdavisProg at gmx.com
Wed Nov 17 13:38:50 PST 2010
On Wednesday 17 November 2010 13:10:19 Matthias Pleh wrote:
> void foo(char[] a) {}
> void bar(char[][] b) {}
>
> int main(string[] args)
> {
> char[4] a;
> char[4][4] b;
> foo(a); // OK: implicit convertion
> bar(b); // Error: cannot implicitly convert
> // char[4u][4u] to char[][]
> }
>
> what is the reason for the different behaviour?
> What's best to pass such multidimensional arrays?
How would even do that conversion? char[4][4] is one solid block of memory.
char[][] is an array of arrays. If you slice b - b[] - you get a char[4][] - so
you have a dynamic array of static arrays. There is no way (as far as I know) to
convert that to a dynamic array of dynamic arrays. As such, the compiler can't
do it implicitly or explicitly. You can probably create a dynamic array of
dynamic arrays and assign each of the internal arrays to to each of the internal
arrays of b, but there's no direct way to do it. You're dealing with two _very_
different types here. While they may be accessed similarly, one is a statically-
allocated block of memory, while the other is references to references and all
on the heap. It's already buggy enough to pass a statically allocated array by
reference (since the function that it's passed to doesn't know that the data is
on the stack rather than the heap and could leak references to it). It would
likely be very difficult to cleanly do that with multi-dimensional static arrays.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list