Dynamic Arrays with TList |
There are two ways to create a dynamically sized array in Delphi. You can use normal Pascal types to declare a large array, and then use dynamic memory allocation to allocate the number of items you really need. An example of this method is shown in Listing 5-1. The problem with this approach is that it defeats Pascal's array bounds checking. If your code were to refer to IntArray^[Count], for example, the Pascal run-time environment would have no way of knowing that this is an invalid reference. You know it is invalid, since you allocate only enough memory to reach index, Count-1. To provide run-time safety, you would need to write custom range checking code. This approach is also difficult to use if the array frequently changes size. Fortunately, Delphi offers an alternative, the TList class.
type { Declare the size of the array to be as large as possible } TIntegerArray = array[0..32760] of Integer; PIntegerArray = ^TIntegerArray; var IntArray: PIntegerArray; I: Integer; begin GetMem(IntArray, Count*SizeOf(Integer)); try for I := 0 to Count-1 do IntArray^[I] := I; DoSomething(IntArray, Count); finally FreeMem(IntArray, Count*SizeOf(Integer)); end; end;
The TList class implements an array of pointers where the array can grow or shrink at run time, and where all index references are checked for validity. Listing 5-2 shows a simple example of how TList can be used. The TList class is very useful, but you need to understand exactly how it works before you can use it.
var List: TList; begin List := TList.Create; try for I := 0 to Count-1 do List.Add(Pointer(I)); DoSomething(List); finally List.Free; end; end;
If you were to refer to List[Count], Delphi would raise an EListError exception because of the invalid index. Thus, TList is safer to use than dynamic array allocation. Also, TList is easy to use for a list than grows or shrinks at run time, as you will learn.
Copyright © 1996 Waite Group Press