Search code examples
arraysdelphidelphi-xe2proceduredeclare

Declaring Arrays of Variable Length in Delphi


I have a procedure in Delphi which currently looks like this:

Procedure Time.TimeDB(algorithm: string; Encode, Decode: InputFunction; N, R: Int);
VAR
    i : LongInt;
    Errors : Array[N] of LongInt;
BEGIN

for i := 0 to N-1 do
  Errors[i] := 0;

END;

I'm given the error that N, as passed to the definition of Errors, is an undeclared identifier, despite declaring it in the procedure definition. N is recognized in the BEGIN-END section, though. Any ideas what's causing this and how I can otherwise declare a variable-length array in the VAR section?


Solution

  • You write array of Int to declare a dynamic array of Ints:

    procedure Time.TimeDB(algorithm: string; Encode, Decode: InputFunction; N, R: Int);
    var
      i: int;
      errors: array of Int;
    begin
    
      SetLength(errors, N);
      for i := 0 to N - 1 do
        Errors[i] := 0;
    
    end;
    

    Also notice that if an array has N elements, then they are indexed 0, 1, ..., N - 1. There is no element indexed N.

    (Also, are you sure you don't mean integer when you write Int?)


    The construct array[M..N] of Int is called a static array. In this case, M and N must be constants, like array[0..15] of TColor. You also got the static array declaration array[TMyType] of TMySecondType where the index will be of type TMyType, as in array[byte] of TColor or array[TFontStyle] of cardinal.