Pointers in Pascal

program Pointers;

uses
  SysUtils;

procedure ZeroVal(var iVal: Integer);
begin
  iVal := 0;
end;

procedure ZeroPtr(iPtr: ^Integer);
begin
  iPtr^ := 0;
end;

var
  i: Integer;
  iPtr: ^Integer;

begin
  i := 1;
  WriteLn('initial: ', i);

  ZeroVal(i);
  WriteLn('zeroval: ', i);

  iPtr := @i;
  ZeroPtr(iPtr);
  WriteLn('zeroptr: ', i);

  WriteLn('pointer: ', IntToHex(NativeUInt(iPtr), 8));
end.

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:

  1. We initialize i with the value 1 and print it.
  2. We call ZeroVal(i), which modifies i directly.
  3. We create a pointer iPtr that points to i using the @ operator.
  4. We call ZeroPtr(iPtr), which modifies the value i through the pointer.
  5. Finally, we print the memory address of i using the IntToHex 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:

$ fpc pointers.pas
$ ./pointers
initial: 1
zeroval: 0
zeroptr: 0
pointer: 00AF7C30

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.