I had code with the basic constructs illustrated by the following:
type
TDynamicArray = array of double ;
var
a : TDynamicArray ;
function Func : TDynamicArray ;
var
b : TDynamicArray ;
begin
SetLength (B, 3) ;
b [0] := 0.0 ;
b [1] := 1.0 ;
b [2] := 2.0 ;
Result := b ; // note 1 -- should use Result := Copy (b, 0, Length (b))
end ;
begin
a := Func ; // note 2 -- should we (or could we) use a := Copy (Func, 0, Length (Func))
end.
It had been working fine until lately when the function started returning empty arrays. I then spot this which enlightens me to the fact that simple assignment isn't correct, I need to use Copy.
Two questions:
- I realise I need 'Copy' on the line marked
Note 1to assign to the function result. Do I need to useCopyalso on the assignment of the function result to arraya(lineNote 2)?. - Why did the compiler allow my construct and what was the compiled code actually doing?
I realise I could try these things and see, but I'm a little spooked by the compiler letting questionable stuff through.
Copy (Func, ...as you show in your comment since it would runFunctwice. But to your ain issue, I'm not sure how Delphi handles a local dynamic array variable. I would go with the copy toresultin the function, or just useresultdirectly.Result.Copywith just one argument and it will copy the entire array, no matter its length. The documentation even says so.