---- Delphi-Talk Discussion List <delphi-talk@elists.org> wrote:
>
> Hello,
> 
> Subject maybe not technically correct, but there is something where
> I have no explanation for it:
> 
> procedure Test(const S: string);
> begin
>    WriteLn(Length(S));
> end;
> 
> procedure TForm1.FormCreate(Sender: TObject);
> var
>    P: PChar;
> begin
>    AllocConsole;
>    GetMem(P, 512);
>    FillChar(P^, 511, ' ');
>    P[511] := #0;
>    Test(P + ^Z);           // displays 256
>    Test(string(P) + ^Z);   // displays 512 wich is correct
>    FreeMem(P);
> end;
> 
> Wy is the length of the first string only 256 ?
> I try this in Delphi 7.

First off I was surprized that you could pass a "naked" PChar as a parameter to 
a routine taking a string parameter like that, it seems to me a bad choice as a 
permissable type coercion.

In any case, in the absence of proper string identification information to the 
contrary (which a naked PChar would lack) the compiler evidently assumes you're 
passing an old style Borlandish short string, which is limited to 255 
characters (as mentioned by another poster).

If you explicitly define the parameter as a Delphi32 long string like so:

  procedure Test(const S: AnsiString);

You get the result you expect.

It's arguable that coercion to short string is a poor assumption in 32-bit 
Delphi, but I think it's also a more conservative assumption and more likely to 
avoid memory overruns or other grief.

Expecting the compiler to second guess what you meant in this case is IMO a bad 
idea. If it were me I wouldn't permit it in the first place.

I'd say the moral of the story is to be explicit about what you mean when 
converting between string representations like this.

Stephen Posey
[EMAIL PROTECTED]
__________________________________________________
Delphi-Talk mailing list -> Delphi-Talk@elists.org
http://www.elists.org/mailman/listinfo/delphi-talk

Reply via email to