Help & Manual authoring tool
How to specify the size of an array at runtime?

Dynamic arrays

Copyright © 2000 Ernesto De Spirito

Pascal Newsletter. Free ezine for Delphi (and Kylix) programmers with articles, news, reviews, tips, trinks, and links to new Delphi content on the web!

Dynamic arrays are arrays that can grow or shrink at runtime to accommodate more or less elements. The declaration of a dynamic array is much like the declaration of a static array, except that the index range is omitted. For example:

var
  a: array of integer;

A dynamic array initially has no elements. You should use the SetLength procedure in your code to assign the number of elements needed. You can call SetLength many times as needed. If the new length is greater than the current number of elements, space for new elements is added, and if it's smaller then the last elements of the array are disposed.

For example SetLength(a, 10) assigns space for 10 elements. Elements in a dynamic array are indexed starting from 0 to one less the Length of the array, so for example the following code can be used to initialize the array elements to zero:

  for i := 0 to Length(a)-1 do
    a[i] := 0;

In the example attached to this article you'll see the use of a dynamic array to store the names of the files in a folder. Naturally, a string list would be better for the task, but a dynamic array was used for a pedagogic purpose.

Multimensional dynamic arrays

A two-dimension dynamic array can be declared this way:

var
  a: array of array of integer;

This way you can assign both dimensions at runtime. The SetLength procedure admits as many NewLength parameters as dimensions. For example SetLength(a, 10, 10) would set the size of the array to an square of 10 x 10.

One interesting thing is that instead of seeing your array as a matrix (i.e. rectangular) you can see it as a vector of vectors that don't necessarily have to have the same number of elements. For example the following code creates a triangular array and initialize its elements with consecutive numbers:

  k := 0;
  SetLength(a, 4);              // 4 rows
  for i := 0 to 3 do begin      // For each row
    SetLength(a[i], i + 1);     //   Set the number of columns
    for j := 0 to i do begin    //   Initialize the row
      a[i,j] := k;
      inc(k);
    end;
  end;
    
          0   1   2   3
        +---+
      0 | 0 |
        +---+---+
      1 | 1 | 2 |
        +---+---+---+
      2 | 3 | 4 | 5 |
        +---+---+---+---+
      3 | 6 | 7 | 8 | 9 |
        +---+---+---+---+
JfControls Library - for Delphi and C++ Builder
Copyright © 2000/2006 Ernesto De Spirito.   All rights reserved.