Reputation: 6015
I want to pass reference of an array to a function that needs the length of array. I want to know if I have to pass its length as well or I can retrieve it from the array reference.
uses
Vcl.Dialogs, System.SysUtils, System.Types;
type
IntegerArray = array[0..$effffff] of Integer; // defined in System
PIntegerArray = ^IntegerArray; // defined in System
procedure Foo(const P: PIntegerArray);
begin
ShowMessage(IntToStr(Length(P^)));
end;
const
A: array[0..2] of Integer = (1, 2, 3);
var
B: TIntegerDynArray;
initialization
Foo(@A);
B := [4, 5, 6];
Foo(@B[0]);
end.
Upvotes: 3
Views: 1059
Reputation: 612954
Your question amounts to the following:
Given the address of the first element of an array, which could be either static or dynamic, can I find the length of that array?
The answer is no. There are two factors in your way.
Upvotes: 5
Reputation: 34899
To accomplish this, you need to declare an open array parameter:
procedure Foo(const A: array of integer);
begin
ShowMessage('Length of array:'+IntToStr(High(A)+1));
end;
Pass both dynamic and static arrays to the procedure, and the arrays length is given by System.High.
Open array : The value, of type Integer, giving the number of elements in the actual parameter, minus one.
Upvotes: 8