why no implicit convertion?

Steven Schveighoffer schveiguy at yahoo.com
Wed Nov 17 13:36:05 PST 2010


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?

char[][] is an array of dynamic arrays.  A dynamic array consists of a length and a pointer
A char[4][4] is a fixed array of fixed arrays.  A fixed array consists of just data, the length is part of the type, and the pointer is implied.

> What's best to pass such multidimensional arrays?

two ways, if you want to support multiple lengths of 4-element char arrays, you could do:

void bar(char[4][])

if you want to support only a 4x4 array, you can do:

void bar(ref char[4][4])

If you want to pass by value, omit the ref, but this will copy all the data and you will not be able to update the original array from within the function.

-Steve


More information about the Digitalmars-d-learn mailing list