Name

Pointer Type

Syntax

type Pointer;

Description

The Pointer type is a generic pointer type. Without using type casts, you can assign any pointer-valued expression to a Pointer-type variable or assign a Pointer-type expression to a variable with a specific pointer type.

Tips and Tricks

  • Because object references are actually pointers, you can freely type cast an object reference to a Pointer and back again.

  • Good programming style is to use typed pointers as much as possible. Types help prevent errors and provide documentation to the person reading and maintaining the code. A common source of errors is typecasting a pointer incorrectly.

Example

// The TList type stores a list of Pointers. Delphi automatically
// converts typed pointers and object references to Pointer.
// Retrieving items from the list is also simple.
procedure TForm1.FormCreate(Sender: TObject);
var
  List: TList;
  I: Integer;
  P: ^Integer;
  F: TForm;
begin
  List := TList.Create;
  List.Add(@I);     // Add takes an argument of type Pointer
  List.Add(Self);

  P := List[0];     // List[0] returns type Pointer
  P^ := 10;
  F := List[1];
  F.Show;

  List.Free;
end;

See Also

Addr Function, Nil Keyword, Ptr Function, $T Compiler Directive, $TypedAddress Compiler Directive, @ Operator

Get Delphi in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.