Can I use dynamic array types unchanged as Var parameters

Using D2010, I would like to do something like this:

procedure SizeArray(var aArr: array of integer; aSize: integer);
begin
  SetLength(aArr,aSize);
end;

But this does not compile. Since my "aArr" parameter is not a dynamic array, this is an open array parameter. And SetLength cannot be called. The only way I know to force a parameter to be a dynamic array is to give it a type name, for example:

type
  TIntArray = array of integer;

procedure SizeArray(var aArr: TIntArray; aSize: integer);
begin
  SetLength(aArr,aSize);
end;

And now the code compiles. And it works fine, for the most part, but it fails:

procedure Test;
var
  a : array of integer;
begin
  SizeArray(a,5);
end;

Since the types of the actual and formal parameters of var must be the same, and the compiler does not recognize the "array of integer" and "TIntArray" as identical types.

, : - var , , " ", - ?

.

+3
3

Pascal, Delphi , , . , , , :

var
  x: array of Integer;

... , . . ; , Kilometers vs Kilograms - , .

( , skamradt), . , TArray<T>, . , array of Integer TArray<Integer>.

TArray<T> :

type
  TArray<T> = array of T;

... .

+10

... absolute var.

procedure SizeArray(var aArr; aSize: integer);
var
  ActArr : Array of Integer absolute aArr;
begin
  SetLength(ActArr,aSize);
end;

var
  Test : Array of Integer;
begin
  SizeArray(Test,5);
  showMessage(IntTostr(High(Test)));  // -- returns 4
end;
+9

No, there is no way to do this. It is part of the Pascal language specification and is unlikely to change.

EDITOR: Scamradt has found a way. Let me repeat that. There is no way to do it safely.

0
source

Source: https://habr.com/ru/post/1721548/


All Articles