Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What needs finalization in a multidimensional dynamic array?

Tags:

arrays

delphi

I use dynamic arrays a great deal and have no problems with the SetLength and Finalize procedures.

I recently had cause to use dynamic arrays where each array element could itself contain a variable number of elements. The declaration is like this:

TScheduleArray =  array of array of array [1..DaysPerWeek] of TShiftType;

The software is working fine, I've not got a problem with how to use this structure. You call SetLength on the main array and then can call SetLength again on each array element. This is working as expected.

SetLength(MyArray, 1);
SetLength(MyArray[0], 2);

My question is this: When I come to free up the resources used for this array, do I just call Finalize on the array variable:

Finalize(MyArray);

or does each array element also need to be Finalized, as each element is a dynamic array itself?

like image 801
J__ Avatar asked Jun 05 '26 22:06

J__


2 Answers

Quote : "You call SetLength on the main array and then can call SetLength again on each array element."

You don't really have to iterate through your arrays.

SetLength() accepts a list of lengths for each dimension.

Example:

SetLength(ScheduleArray,200,15,35);

Is the same as:

SetLength(ScheduleArray,200);
for i:=low(ScheduleArray) to high(ScheduleArry) do
begin
  SetLength(ScheduleArray[i],15);
  for j:=low(ScheduleArray[i]) to high(ScheduleArray[i]) do
    SetLength(ScheduleArray[i,j],35);
end;
like image 66
Wouter van Nifterick Avatar answered Jun 08 '26 12:06

Wouter van Nifterick


The arrays are managed by the compiler and don't need to be finalized. If TShiftType is a class, you'll have to free the objects manually, one at a time, but the array itself will be disposed of properly when it goes out of scope.

like image 32
Mason Wheeler Avatar answered Jun 08 '26 13:06

Mason Wheeler