tags:

views:

342

answers:

3

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?

+4  A: 

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.

Mason Wheeler
Ah yes I see in the Delphi help "If the variable specified in a call to Finalize contains no long strings, variants, or interfaces, the compiler eliminates the call and generates no code for it."TShiftType is an enumerated type, so no objects.So all this time I've been careful enough to call Finalize, the compiler has been eliminating the call?!
_J_
Yep! Dynamic arrays and records are taken care of for you.
Mason Wheeler
+3  A: 

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;
Wouter van Nifterick
Thank you, that's useful to know.
_J_
Although this doesn't work if your array is not rectangular. (Also, although interesting, it's not an answer to the question.)
Richard A
A: 

hi to free any dynamic array just assign it to nil for example: a:array of array of integer;

to free it use: a:=nil;

waleed shorbagy