Technical Information Database
TI428D.txt - Declaring an array on the heap
Category :Object Pascal
Platform :All-32Bit
Product :
Description:
The following program, HEAPARY.PAS, demonstrates
how to place an array on the heap. Programmers
need to do this when they get errors saying that
there are "too many variables" or that they are out
of data space.
The solution to the above errors is simply to
move an array up on the heap by creating a pointer
to the array. Notice that the actual definition of
the array is in the TYPE section, not the VAR
section. If you write a statement like:
var MyArray: array[0..100] of Char
then you are allocating memory in the data segment,
which is what you want to avoid. The solution is to
define the array in the TYPE section, and then
declare it in the VAR section:
var MyArray: PMyArray;
where PMyArray is a pointer to an array. To see the complete
code for this type of example, refer to the HEAPARY program
shown below.
The $X is just so HEAPARY.PAS can use ReadKey
without returning a result, the FlushKeyBuffer and Pause
methods are thrown in case you are interested. The body
of the program and the Type declaration are the parts
you want to look at. Always remember to dispose memory
allocated with New!
Program HeapAry;
{$X+}
Uses
Dos,
Crt;
Type
PMyArray = ^TMyArray;
TMyArray = array[0..999] of LongInt;
procedure FlushKeyBuffer;
var Recpack : registers;
begin
with recpack do begin
Ax := ($0c shl 8) or 6;
Dx := $00ff;
end;
Intr($21,recpack);
end;
procedure Pause;
begin
FlushKeyBuffer; { Make sure key buffer is empty! }
ReadKey; { Pause }
end;
var
MyAry: PMyArray;
i: Integer;
begin
ClrScr;
New(MyAry); { Allocate the memory on the heap }
for i := 0 to 999 do { Fill out array }
MyAry^[i] := i;
for i := 500 to 510 do { Write the array to the screen }
WriteLn(MyAry^[i]);
Pause;
Dispose(MyAry); { Dispose memory! }
end.
Reference:
4/22/99 1:01:59 PM
Last Modified: 01-SEP-99