Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2023-03

pointer to char vs pchar

5 messages · 5 people · –

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Benito van der Zander

Hallo,

why is a pointer to a char not a pchar (for type helpers)?

program Project1;
{$Mode objfpc}{$H+} {$ModeSwitch typehelpers}
type TPcharHelper = type helper for pchar
   function toString(length: integer): string;
end;
function TPcharHelper.toString(length: integer): string;
begin
   SetString(result, self, length);
end;
var c: char;
begin
   c := 'x';
   writeln((@c).toString(1)); //does not compile
   writeln(pchar(@c).toString(1));
end.

Bye,

Benito

Reply by email

Martin Frb
to Benito van der Zander
Benito van der Zander wrote
why is a pointer to a char not a pchar (for type helpers)?

My guess: For the same reason that "p2" fails in the below. Distinct type. May be assignment compatible, but a type of it's own.

Imagine you had a different helper, with a different "toString" on pchar2, then which one should @char get?

program Project1;
{$Mode objfpc}{$H+} {$ModeSwitch typehelpers}
type
   pchar = ^char;
   pchar2 = ^char;
type TPcharHelper = type helper for pchar
   function toString(length: integer): string;
end;
function TPcharHelper.toString(length: integer): string;
begin
end;
var
   p: pchar;
   p2: pchar2;
begin
   p.toString(1);
   p2.toString(1);  // error
end.

Reply by email

Peter B
to Martin Frb
Martin Frb wrote 5 lines
On 24/03/2023 15:04, Benito van der Zander via fpc-pascal wrote: > why is a pointer to a char not a pchar (for type helpers)? My guess: For the same reason that "p2" fails in the below. Distinct type. May be assignment compatible, but a type of it's own.

My understanding is that pchars are supposed to be null terminated, while the char in a pointer to a char might not be.

Reply by email

Michael Van Canneyt
to Peter B
Peter B wrote 9 lines
On 24/03/2023 14:29, Martin Frb via fpc-pascal wrote: > On 24/03/2023 15:04, Benito van der Zander via fpc-pascal wrote: >> why is a pointer to a char not a pchar (for type helpers)? > > My guess: For the same reason that "p2" fails in the below. Distinct type. > May be assignment compatible, but a type of it's own. My understanding is that pchars are supposed to be null terminated, while the char in a pointer to a char might not be.

This is not quite correct.

By itself, a PChar can point to anything.
Only if you typecast a valid ansistring to a pchar then the result of the typecast is guaranteed to be null-terminated.

Michael.

Reply by email