PChar – Null terminated strings

[next] [prev] [prev-tail] [tail] [up]

#### 3.2.7 PChar – Null terminated strings

Free Pascal supports the Delphi implementation of the PChar type. PChar is defined as a pointer to a Char type, but allows additional operations. The PChar type can be understood best as the Pascal equivalent of a C-style null-terminated string, i. e. a variable of type PChar is a pointer that points to an array of type Char, which is ended by a null-character (#0). Free Pascal supports initializing of PChar typed constants, or a direct assignment. For example, the following pieces of code are equivalent:

program one;
var P : PChar;
begin
P := 'This is a null-terminated string.';
WriteLn (P);
end.

Results in the same as

program two;
const P : PChar = 'This is a null-terminated string.';
begin
WriteLn (P);
end.

These examples also show that it is possible to write the contents of the string to a file of type Text. The strings unit contains procedures and functions that manipulate the PChar type as in the standard C library. Since it is equivalent to a pointer to a type Char variable, it is also possible to do the following:

Program three;
Var S : String[30];
P : PChar;
begin
S := 'This is a null-terminated string.'#0;
P := @S[1];
WriteLn (P);
end.

This will have the same result as the previous two examples. Null-terminated strings cannot be added as normal Pascal strings. If two PChar strings must be concatenated; the functions from the unit strings must be used.

However, it is possible to do some pointer arithmetic. The operators + and - can be used to do operations on PChar pointers. In table (3.6), P and Q are of type PChar, and I is of type Longint.

Table 3.6: PChar pointer arithmetic

Operation | Result
P + I | Adds I to the address pointed to by P.
I + P | Adds I to the address pointed to by P.
P - I | Subtracts I from the address pointed to by P.
P - Q | Returns, as an integer, the distance between two addresses
| (or the number of characters between P and Q)

[next] [prev] [prev-tail] [front] [up]