Quick start manual
5-20
Delphi Language Guide
Structured types
Dynamic arrays
Dynamic arrays do not have a fixed size or length. Instead, memory for a dynamic
array is reallocated when you assign a value to the array or pass it to the SetLength
procedure. Dynamic-array types are denoted by constructions of the form
array of baseType
For example,
var MyFlexibleArray: array of Real;
declares a one-dimensional dynamic array of reals. The declaration does not allocate
memory for MyFlexibleArray. To create the array in memory, call SetLength. For
example, given the previous declaration,
SetLength(MyFlexibleArray, 20);
allocates an array of 20 reals, indexed 0 to 19. Dynamic arrays are always integer-
indexed, always starting from 0.
Dynamic-array variables are implicitly pointers and are managed by the same
reference-counting technique used for long strings. To deallocate a dynamic array,
assign nil to a variable that references the array or pass the variable to Finalize; either
of these methods disposes of the array, provided there are no other references to it.
Dynamic arrays are automatically released when their reference-count drops to zero.
Dynamic arrays of length 0 have the value nil. Do not apply the dereference operator
(^) to a dynamic-array variable or pass it to the New or Dispose procedure.
If X and Y are variables of the same dynamic-array type, X := Y points X to the same
array as Y. (There is no need to allocate memory for X before performing this
operation.) Unlike strings and static arrays, COPY-ON-WRITE is not employed for
dynamic arrays, so they are not automatically copied before they are written to. For
example, after this code executes,
var
A, B: array of Integer;
begin
SetLength(A, 1);
A[0] := 1;
B := A;
B[0] := 2;
end;
the value of A[0] is 2. (If A and B were static arrays, A[0] would still be 1.)
Assigning to a dynamic-array index (for example, MyFlexibleArray[2] := 7) does not
reallocate the array. Out-of-range indexes are not reported at compile time.