views:

247

answers:

4

In Delphi, it is possible to create an array of the type

var
  Arr: array[2..N] of MyType;

which is an array of N - 1 elements indexed from 2 to N.

If we instead declare a dynamic array

var
  Arr: array of MyType

and later allocate N - 1 elements by means of

SetLength(Arr, N - 1)

then the elements will be indexed from 0 to N - 2. Is it possible to make them indexed from 2 to N (say) instead?

+11  A: 

No, in Delphi dynamic arrays are always indexed from zero.

vcldeveloper
A: 

The only thing that you can do that mimics this behaviour is using pointers..

type
  TMyTypeArr = array [ 0..High(Integer) div sizeof( MyType ) - 1 ] of Mytype;
  PMyTypeArr = ^TMyTypeArr;
var
  x: ;
  A: PMyTypeArr;
begin
  SetLength( A, 2 );
  x := PMyTypeArr( @A[ 0 ] ); Dec( PMyType( x ), 2 ); // now [2,4> is valid.
  x[2] := Get_A_MyType();
end;  

Please note that you lose any range checking, and combine that with non zero starting arrays is a VERY VERY bad idea!

Ritsaert Hornstra
A: 

If you really need this indexing, then you could write a simple "translation" function, which will receive an index figure in the range from 2 to N and will return an index from 0 to N-2, just by subtracting 2 from the parameter, for example:

function translate(i : integer) : integer;
begin
  result := i - 2;
end;

And you could call your array like this:

array[translate(2)]

Of course, you could in addition do range checking within the function, and maybe you could give it a shorter name.

Hope this helps

Flo
A: 

YES! By using a trick!
First declare a new type. I use a record type instead of a class since records are a bit easier to use.

type
  TMyArray = record
  strict private
    FArray: array of Integer;
    FMin, FMax:Integer;
    function GetItem(Index: Integer): Integer;
    procedure SetItem(Index: Integer; const Value: Integer);
  public
    constructor Create(Min, Max: integer);
    property Item[Index: Integer]: Integer read GetItem write SetItem; Default;
    property Min: Integer read FMin;
    property Max: Integer read FMax;
  end;

With the recordtype defined, you now need to implement a bit of code:

constructor TMyArray.Create(Min, Max: integer);
begin
  FMin := Min;
  FMax := Max;
  SetLength(FArray, Max + 1 - Min);
end;

function TMyArray.GetItem(Index: Integer): Integer;
begin
  Result := FArray[Index - FMin];
end;

procedure TMyArray.SetItem(Index: Integer; const Value: Integer);
begin
  FArray[Index - FMin] := Value;
end;

With the type declared, you can now start to use it:

var
  Arr: TMyArray;
begin
  Arr := TMyArray.Create(2, 10);
  Arr[2] := 10;

It's actually a simple trick to create arrays with a specific range and you can make it more flexible if you like. Or convert it to a class. Personally, I just prefer records for these kinds of simple types.

Workshop Alex