Pointers in Pascal
Pascal supports pointers, allowing you to pass references to values and records within your program.
We’ll show how pointers work in contrast to values with two procedures: ZeroVal
and ZeroPtr
. ZeroVal
has a var
parameter, which is passed by reference in Pascal. ZeroVal
will directly modify the i
variable in the calling procedure.
ZeroPtr
takes an ^Integer
parameter, which is a pointer to an Integer. The iPtr^
syntax in the procedure body then dereferences the pointer, allowing us to modify the value it points to. Assigning a value to a dereferenced pointer changes the value at the referenced address.
In the main program:
- We initialize
i
with the value 1 and print it. - We call
ZeroVal(i)
, which modifiesi
directly. - We create a pointer
iPtr
that points toi
using the@
operator. - We call
ZeroPtr(iPtr)
, which modifies the valuei
through the pointer. - Finally, we print the memory address of
i
using theIntToHex
function to convert the pointer to a hexadecimal string.
To run this program, save it as pointers.pas
and compile it using a Pascal compiler like Free Pascal:
Note that ZeroVal
changes the i
in the main program because it’s passed by reference. ZeroPtr
also changes i
because it has a pointer to the memory address of that variable.
Pascal’s pointer syntax is different from some other languages:
^
is used to declare a pointer type@
is used to get the address of a variable^
is also used to dereference a pointer
This example demonstrates basic pointer usage in Pascal, showing how they can be used to modify values indirectly.