Posted by John, DelphiLand Team on May 26, 2008
In Reply to delphi dynamic array posted by Albert C p16043 on
May 25, 2008
: How to use dynamic array in Delphi? Is it much different from usual (static) array? Do I have to release (de-allocate) the memory after using it?
In Delphi, you declare static arrays such as:
aS: array[1..20] of string;
You can also declare dynamic arrays, that don't have a fixed size. For example:
aDS: array of string;
Before using a dynamic array, you must set its size, its "length". This can be done with the SetLength procedure, such as:
Now you've allocated memory for an array of 20 strings, indexed 0 to 19. Note that dynamic arrays are always integer-indexed, always starting from 0.
For a two-dimensional dynamic array of integers, use the following code:
var aD2I: array of array of integer; begin // An array of 100 by 2 elements: SetLength(aDI2, 100, 2); // Use the array: aDI2[0,0] := 5; aDI2[0,1] := 7; aDI2[99,1] := 200; // and so on... end;
You don't have to de-allocate (release, free) the memory after using the array, Delphi takes care
of this automatically.
Anyway, you are allowed to free the memory and erase all the data of the dynamic array by assigning nil to it, for example:
aDS := nil;