The Pointer Type


The other Delphi pointer type is the Pointer. The Pointer is the untyped pointer type that can be used to point to a variable of any data type. To use the value to which an untyped pointer points, you first have to typecast the untyped pointer to another pointer type and dereference it. Casting to another pointer type is simple because every data type in Delphi already has a pointer counterpart. For instance, a pointer to a Char is PChar, a pointer to a string is PString, a pointer to an integer is PInteger, etc.

Listing 9-2 shows how to use the Pointer type and how to typecast it to other pointer types.

Listing 9-2: Using an untyped pointer

image from book
program Project1; {$APPTYPE CONSOLE} uses   SysUtils; var   I: Integer;   C: Char;   P: Pointer;     { untyped pointer } begin   I := 2004;   C := 'd';   P := @I;      { point to I }   { typecast to an integer pointer, dereference, and increment }   Inc(PInteger(P)^);   WriteLn('I = ', PInteger(P)^);   P := @C;      { point to C }   { typecast to a char pointer, dereference, and convert to 'D' }   PChar(P)^ := Chr(Ord(PChar(P)^) - 32);   WriteLn('C = ', PChar(P)^);   ReadLn; end.
image from book

To be completely safe when using pointers, you should make sure that the pointer references a valid memory location. To see if the pointer references an invalid memory location, you can use the reserved word nil. The reserved word nil is a constant value that denotes an invalid memory location. A nil pointer doesn't reference anything:

program Project1; {$APPTYPE CONSOLE} uses   SysUtils; var   I: Integer = 2005;   P: ^Integer = @I; { automatically point to I } begin   WriteLn(P^);      { P points to I }   P := nil;         { P points to nothing }   ReadLn; end.



Inside Delphi 2006
Inside Delphi 2006 (Wordware Delphi Developers Library)
ISBN: 1598220039
EAN: 2147483647
Year: 2004
Pages: 212
Authors: Ivan Hladni

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net