How do I pass multidimensional static arrays to functions expecting

Timon Gehr timon.gehr at gmx.ch
Tue Aug 30 04:33:01 PDT 2011


On 08/30/2011 01:06 PM, bearophile wrote:
> Timon Gehr Wrote:
>
>> On 08/30/2011 03:20 AM, bearophile wrote:
>>> Timon Gehr:
>>>
>>>> bar(array(map!((int[] a){return a;})(multi[])));
>>>
>>> Simpler:
>>> bar( array(map!q{ a[] }(multi[])) );
>>
>> And buggy. It returns slices of a local stack frame, because static
>> arrays are value types.
>
> q{ a[] } does the same thing as (int[] a){return a;}, both return a slice of memory on the stack. Using a dynamic array (a slice) that uses memory allocated on the stack is correct. You just have to know what you are doing. It's the same as passing a fixed-sized array to a function that expects a dynamic slice.
>

No, what they do is very different. Yours creates a new stack frame, 
copies the data into it and then returns invalid slices to the stack 
frame that has now disappeared. Mine returns slices to the enclosing 
stack frame, which is perfectly valid.

If you are not convinced, just try to pass a 2D static array to the 
following function using your method:

void bar(int[][] a){writeln(a);}

It won't work.



More information about the Digitalmars-d-learn mailing list