saastn
saastn

Reputation: 6015

Is it possible to get length of (static/dynamic) arrays from their references?

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

Answers (2)

David Heffernan
David Heffernan

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.

  1. You can't tell whether the array is dynamic or static.
  2. Even if you knew the array was static, you would not be able to find its length without compile time knowledge of its type.

Upvotes: 5

LU RD
LU RD

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

Related Questions