[fpc-pascal] Dynamic array as return type of functions
Michalis Kamburelis
michalis.kambi at gmail.com
Wed May 23 10:06:25 CEST 2007
Christos Chryssochoidis wrote:
> Hi,
>
> I tried to write some function that returned a dynamic array, and
> realized that this isn't allowed. Why? After all one can specify an
> array of variable length as type for variables... Furthermore - if I'm
> not mistaken - a dynamic array is implemented internally as a pointer,
> and so there wouldn't be any runtime overhead for returning a dynamic
> array from a function.
>
It *is* allowed. The only trick is that you have to declare a type for
your dynamic array, i.e. you have to write something like
type TDynInts = array of Integer;
function MakeArray: TDynInts;
instead of
function MakeArray: array of Integer;
This quick example compiles fine in objfpc mode:
type
TDynInts = array of Integer;
function MakeArray: TDynInts;
begin
SetLength(Result, 2);
Result[0] := 0;
Result[1] := 1;
end;
var
A: TDynInts;
begin
A := MakeArray;
Writeln(A[0], ' ', A[1]);
end.
Michalis
More information about the fpc-pascal
mailing list