Working with dynamic arrays in Delphi

One advantage of Delphi’s dynamic arrays is that they are automatically freed once they go out of scope. That simplifies memory management and gives you more flexibility on your applications.

You can declare a dynamic array like this:

Customers: array of string;

 

Before adding an element, you have to call the SetLength function to specify the number of elements you are going to use (3 in this case):

SetLength(Customers, 3);

 

Now you can go ahead adding values:

Customers[0] := 'John';
Customers[1] := 'Mark';
Customers[2] := 'Tom';

Unlike static arrays, the first element of a dynamic array is 0.

It is not necessary to explicitly free a dynamic array, however if you need to do it, you can do it like this:

Customers := nil;

 

To get the number of items in your array you can use the Length function too:

Length(Customers);

 

One Reply to “Working with dynamic arrays in Delphi”

Leave a Reply