In Delphi, dynamic arrays are always zero-based, meaning their indices start at 0. This design choice ensures consistency and aligns with the behavior of dynamic arrays in many programming languages[1].
If you require an array with a different starting index, such as 1 or any other value, you can create a custom data structure to simulate this behavior. One approach is to define a record that encapsulates the dynamic array and manages the offset internally. Here's an example:
type
TCustomArray<t> = record
private
FData: array of T;
FOffset: Integer;
function GetItem(Index: Integer): T;
procedure SetItem(Index: Integer; const Value: T);
public
constructor Create(LowIndex, HighIndex: Integer);
property Items[Index: Integer]: T read GetItem write SetItem; default;
end;
constructor TCustomArray<t>.Create(LowIndex, HighIndex: Integer);
begin
FOffset := LowIndex;
SetLength(FData, HighIndex - LowIndex + 1);
end;
function TCustomArray<t>.GetItem(Index: Integer): T;
begin
Result := FData[Index - FOffset];
end;
procedure TCustomArray<t>.SetItem(Index: Integer; const Value: T);
begin
FData[Index - FOffset] := Value;
end;
With this structure, you can create an array that appears to have a custom lower bound:
var
MyArray: TCustomArray<integer>;
begin
MyArray := TCustomArray<integer>.Create(1, 10); // Creates an array indexed from 1 to 10
MyArray[1] := 42; // Accesses the first element
end;
This approach allows you to work with arrays that have non-zero-based indices while leveraging Delphi's dynamic array capabilities[2].