Free Pascal supports the use of pointers. A variable of the type Pointer contains an address in memory, where the data of another variable may be stored.
Pointers can be typed, which means that they point to a particular kind of data. The type of this data is known at compile time.
Consider the following example:
Program pointers; type Buffer = String[255]; BufPtr = ^Buffer; Var B : Buffer; BP : BufPtr; PP : Pointer; etc..
In this example, BP is a pointer to a Buffer type; while B is a variable of type Buffer. B takes 256 bytes memory, and BP only takes 4 bytes of memory (enough to keep an adress in memory).
Remark: Free Pascal treats pointers much the same way as C does. This means that you can treat a pointer to some type as being an array of this type. The pointer then points to the zeroeth element of this array. Thus the following pointer declaration
Var p : ^Longint;Can be considered equivalent to the following array declaration:
Var p : array[0..Infinity] of Longint;The reference
P^
is then the same as p[0]. The following program
illustrates this maybe more clear:
program PointerArray; var i : longint; p : ^longint; pp : array[0..100] of longint; begin for i:=0 to 100 do pp[i]:=i; { Fill array } p:=@pp[0]; { Let p point to pp } for i:=0 to 100 do if p[i]<>pp[i] then writeln ('Ohoh, problem !') end.
Free Pascal supports pointer arithmetic as C does. This means that, if P is a typed pointer, the instructions
Inc(P); Dec(P);Will increase, respecively descrease the address the pointer points to with the size of the type P is a pointer to. For example
Var P : ^Longint; ... Inc (p);will increase P with 4.