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

Jonas Maebe jonas at zeus.rug.ac.be
Fri Jul 19 10:06:52 CEST 2002

On Fri, 19 Jul 2002, Nikolai Zhubr 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

Yes and no. In the above example, "pchar(@st[1])" is automatically
converted to an (ansi?)string. So the end result is that you are adding
two strings.

> next one:
> type
>   HonestPChar = ^Char;
> var
>   st: string[10] = 'Hello';
> begin
>   writeln(HonestPChar(@st[1]) + ' !!!');
> end.
> Delphi says:
> Error: Incompatible types: 'string' and 'HonestPChar'

That's because pchar is a "special" type. For example, in TP/Delphi you
can't access pointer types like arrays (so normally, st[1] already should
fail). In FPC this is the same: in the type conversion code, a lot of
explicit checks for pchars are done, which fail when you define your own
custom type (since in Pascal, two different types are never the same, even
if they have exactly the same definition)

> BTW, this doesn't fit well enough in my head ;) yet. Its like C belch
> or something... I'm afraid of pchars.

The magic compiler stuff can indeed be quite confusing if you don't know
how things are handled.


More information about the fpc-pascal mailing list