Quick start manual

5-28
Delphi Language Guide
Pointers and pointer types
The symbol ^ has two purposes, both of which are illustrated in our example. When
it appears before a type identifier—
^typeName
—it denotes a type that represents pointers to variables of type typeName. When it
appears after a pointer variable—
pointer^
—it dereferences the pointer; that is, it returns the value stored at the memory address
held by the pointer.
Our example may seem like a roundabout way of copying the value of one variable
to another—something that we could have accomplished with a simple assignment
statement. But pointers are useful for several reasons. First, understanding pointers
will help you to understand the Delphi language, since pointers often operate behind
the scenes in code where they don’t appear explicitly. Any data type that requires
large, dynamically allocated blocks of memory uses pointers. Long-string variables,
for instance, are implicitly pointers, as are class instance variables. Moreover, some
advanced programming techniques require the use of pointers.
Finally, pointers are sometimes the only way to circumvent Delphi’s strict data
typing. By referencing a variable with an all-purpose Pointer, casting the Pointer to a
more specific type, and then dereferencing it, you can treat the data stored by any
variable as if it belonged to any type. For example, the following code assigns data
stored in a real variable to an integer variable.
type
PInteger = ^Integer;
var
R: Single;
I: Integer;
P: Pointer;
PI: PInteger;
begin
ƒ
P := @R;
PI := PInteger(P);
I := PI^;
end;
Of course, reals and integers are stored in different formats. This assignment simply
copies raw binary data from R to I, without converting it.
In addition to assigning the result of an @ operation, you can use several standard
routines to give a value to a pointer. The New and GetMem procedures assign a
memory address to an existing pointer, while the Addr and Ptr functions return a
pointer to a specified address or variable.
Dereferenced pointers can be qualified and can function as qualifiers, as in the
expression P1^.Data^.
The reserved word nil is a special constant that can be assigned to any pointer. When
nil is assigned to a pointer, the pointer doesn’t reference anything.