Dynamic array

From Lazarus wiki
Revision as of 03:14, 16 January 2010 by Amiso (talk | contribs)
Jump to navigationJump to search

An dynamic array is a type that in very similar to the array type, but allows more flexibility since the size of this array does not need to be known before the actual execution of the program. The declaration part is just as simple as the static array:

 var
 ...
 MyVariable : array of type;
 ...

Its dimensions can be set or modified whenever needed during the execution of the program by using the statement:

 begin
 ...
  SetLength (MyVariable, ItsLength);
 ...
 end

You must include one or more statements in your program in order to create, expand, or truncate your array.

The array is located on the heap by the dynamic memory allocator and is freed on the program or procedure exit.

The individual elements can be accessed by the same technique as the static arrays:

 ...
 MyVariable[18] := 123;
 ...
 MyOtherVariable := Myvariable[0];
 ...

The index of a dynamic array is zero based, ie. it MUST be whittin the range from 0 to (Length-1). It is not possible to change this to a ONE based system.