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
P^
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
I := 0;
while (I < MaxLen) and (Source[I] <> #0) do
begin
Dest[I] := UpCase(Source[I]);
Inc(I);
end;
Dest[I] := #0;
Result := Dest;
end;
Dostları ilə paylaş: