[fpc-pascal]What exactly is Pchar good for ?

Giovanni Premuda gpremuda at softwerk.it
Fri Jul 19 02:52:32 CEST 2002


----- Original Message -----
From: "Nikolai Zhubr" <s001 at hotbox.ru>

> Thursday, 18 July, 2002, 23:16:12, Martyn Ranyard wrote:
> [...]
> > This doesn't seem right - a PChar is just a pointer to a character,
where the
>
> Consider the following example (for Delphi):
>
> var
>   st: string[10] = 'Hello';
> begin
>   writeln(PChar(@st[1]) + ' !!!');
> end.
>
> The output is:
> Hello !!!
> Does this mean we can add strings to pointers? No. Consider the
> next one:
>
> type
>   HonestPChar = ^Char;
> var
>   st: string[10] = 'Hello';
> begin
>   writeln(HonestPChar(@st[1]) + ' !!!');
> end.

A PChar is definitely a pointer to char! Strings aren't
I have only encountered a problem with more than 255 character using
StrPCopy (or maybe StrPas) in Delphi.
Most probably just because they are no longer needed, as Delphi allows you
to typecast directly between (Ansi)string and PChar;

> Delphi says:
> Error: Incompatible types: 'string' and 'HonestPChar'

var
  st: PChar = 'Hello';
begin
  writeln(String(st) + ' !!!');
end.

This will work. The + operator works only with strings, not with PChars.
BTW, specifying the length of a string will make it a ShortString, which is
not compatible with PChars.

> >  I would have thought that the code behind ansistrings are pchars, but I
may
> > be wrong.
>
> Delphi's rtl handles strings' operations independently of pchars
> whenever possible, iirc. (That is, when not mixed, etc.)

No, Delphi (Ansi)Strings are dynamically allocated and null terminated like
PChars, and have their lenght prepended like old stings (ShortString or
string[xx])

--
Giovanni Premuda
SoftWerk sas





More information about the fpc-pascal mailing list