Using Pointers Arrays and String Constants

To manipulate null-terminated strings, it is often necessary to use pointers. (See Pointers and pointer types.) String constants are assignment-compatible with the PChar and PWideChar types, which represent pointers to null-terminated arrays of Char and WideChar values. For example, var P: PChar; P := 'Hello world!'

points p to an area of memory that contains a null-terminated copy of 'Hello world!' This is equivalent to const TempString: array[0..12] of Char = 'Hello world!'; var P: PChar;

You can also pass string constants to any function that takes value or const parameters of type PChar or PWideChar - for example strUpper('Hello world!'). As with assignments to a PChar, the compiler generates a null-terminated copy of the string and gives the function a pointer to that copy. Finally, you can initialize PChar or PWideChar constants with string literals, alone or in a structured type. Examples:

const

Message: PChar = 'Program terminated'; Prompt: PChar = 'Enter values: ';

Digits: array[0..9] of PChar = ('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine');

Zero-based character arrays are compatible with PChar and PWideChar. When you use a character array in place of a pointer value, the compiler converts the array to a pointer constant whose value corresponds to the address of the first element of the array. For example, var

MyArray: array[0..32] of Char; MyPointer: PChar; begin

MyArray := 'Hello'; MyPointer := MyArray; SomeProcedure(MyArray); SomeProcedure(MyPointer); end;

This code calls SomeProcedure twice with the same value.

A character pointer can be indexed as if it were an array. In the previous example, MyPointer[0] returns h. The index specifies an offset added to the pointer before it is dereferenced. (For PWideChar variables, the index is automatically multiplied by two.) Thus, if p is a character pointer, P[0] is equivalent to pa and specifies the first character in the array, P[1] specifies the second character in the array, and so forth; p[-1] specifies the 'character' immediately to the left of P[0]. The compiler performs no range checking on these indexes.

The strUpper function illustrates the use of pointer indexing to iterate through a null-terminated string:

function strUpper(Dest, source: PChar; MaxLen: Integer): PChar; var

I: Integer; begin

while (I < MaxLen) and (source[I] <> #0) do begin

Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook


Post a comment