3

I am trying to pass some strings to an dynamic string array in this case it is working:

procedure DoSomeThing(in_cmd: string; var out_strs: array of string);
begin
  ..
  for n := low(out_strs) to high(out_strs) do
    begin
      out_strs[n] :='bla bla';
    end;
end;

In application using as:

.
.
.
SetLength(my_out_str, sizer);

DoSomeThing('do it now', my_out_str);
.
.

But I want to SetLength of my_out_str from in the procedure. Is it possible?

Kromster
  • 7,181
  • 7
  • 63
  • 111
  • Read this: http://stackoverflow.com/questions/22140387 This is a known gotcha, its roots are in very very very old days when Pascal (not even Delphi yet) did not had dynamic arrays at all... – Arioch 'The Apr 21 '16 at 10:39

1 Answers1

8

Yes, it is possible, but you have to declare the parameter with a previously defined dynamic array type. you are currently using an open array instead.

type
  TStrDynArray = array of string;

procedure DoSomeThing(in_cmd:string; var out_strs: TStrDynArray);
begin
  SetLength(out_strs, 2 * Length(inn_cmd));
  ...

Or, use TArray<string> if generics are available (from Delphi 2009)

procedure DoSomeThing(in_cmd:string; var out_strs: TArray<string>);
begin
  SetLength(out_strs, 2 * Length(inn_cmd));

The reason for this is that array of x in one context is not the same as array of x in another context.

In a type declaration

type
  TDynamicArray = array of string; 

Is a dynamic array type, which can be resized. Dynamic arrays were introduced in Delphi 4.

In a parameter definition

procedure Test(var X: array of string);

Is an open array parameter which means that it will accept arrays of different sizes as input. It just takes a pointer (i.e. reference) to the first element, and the index of the last element in the array. It does not know or care whether the input array is a dynamic array or a static array, and thus will not allow the length to be resized.

Open array parameters predate Delphi 1.

Further reading
http://rvelthuis.de/articles/articles-openarr.html

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
MBo
  • 77,366
  • 5
  • 53
  • 86