next up previous contents index
Next: Procedural types Up: Types Previous: Structured Types

Pointers

Free Pascal supports the use of pointers. A variable of the pointer type contains an address in memory, where the data of another variable may be stored.


Pointer types

syntdiag1804

As can be seen from this diagram, pointers are typed, which means that they point to a particular kind of data. The type of this data must be known at compile time.

Dereferencing the pointer (denoted by adding ^ after the variable name) behaves then like a variable. This variable has the type declared in the pointer declaration, and the variable is stored in the address that is pointed to by the pointer variable.

Consider the following example:
listing1745
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
listing1756
Can be considered equivalent to the following array declaration:
listing1758
The difference is that the former declaration allocates memory for the pointer only (not for the array), and the second declaration allocates memory for the entire array. If you use the former, you must allocate memory yourself, using the Getmem function.

The reference P^ is then the same as p[0]. The following program illustrates this maybe more clear:
listing1763

Free Pascal supports pointer arithmetic as C does. This means that, if P is a typed pointer, the instructions
listing1768
Will increase, respectively descrease the address the pointer points to with the size of the type P is a pointer to. For example
listing1771
will increase P with 4. You can also use normal arithmetic operators on pointers, that is, the following are valid pointer arithmetic operations:
listing1774
Here, the value that is added or substracted is not multiplied by the size of the type the pointer points to.


next up previous contents index
Next: Procedural types Up: Types Previous: Structured Types

Michael Van Canneyt
Fri Sep 25 09:15:40 MEST 1998