Strings start at index 1, Dynamic Arrays at index 0, Pchars start at index 0

From: Skybuck Flying (nospam_at_hotmail.com)
Date: 10/31/04


Date: Sun, 31 Oct 2004 20:07:22 +0100

Hi,

*sigh*... yes it's me again.. Skybuck... :) you're regular Delphi nagger =D

It's time for me to *nag* again about Delphi...

What's wrong with delphi times time your mind thinks ? :)

Well let me tell you :P

INCONSISTENCY for Strings v Dynamic Arrays v Pchars

*Huuh sigh*

Simply said:

Strings start at index 1.
Dynamic arrays at index 0.
Pchars start at index 0.

Why is this bad ?

Because if somebody has to write an algorithm to work with strings this is
going to bite him in the ass.

Because if he uses Pchars and/or Strings... or switches types somewhere
along the line.. his algorithm will be off by 1 ;)

Sounds familiar ? Yes for me it does sound familiair... "exploiters" use
this off by 1 bug to exploit all kinds of stuff ;)

I accidently stumbled upon this inconsistency the last day when I asked
about constant strings and wanting to send them over the network.

Yeah... so where is the inconsistency located exactly:

Well it's located between array and pointer/pchar.

The array starts at index 1... but the pointer/pchar simply starts at offset
0.

Look at this code:

const
 const_string : string = 'Hello World';

procedure TForm1.Button1Click(Sender: TObject);
var
 s : string;
begin

 s := 'Hello World';

// ShowMessage( s[0] ); // element inaccessable.
 ShowMessage( s[1] );

// ShowMessage( const_string[0] ); // element inaccessable, thank god it
consistent with the above ;)
 ShowMessage( const_string[1] ); // element inaccessable, thank god it
consistent with the above ;)

 // but it is ofcourse inconsistent with dynamic arrays... and c arrays
etc...
 // man... that's bad... never forget that strings start at index 1.

 // now it gets really interesting... because a day ago I wrote this code
and suprise surprise
 // it actually worked ;)

 ShowMessage( char( pointer(const_string)^) ); // what is going on here ?
              // apperently string point to the first character.
              // which is odd enough at index 1.

 ShowMessage( Pchar(const_string)[0] ); // this should work. yup..
Inconsistent *SIGH*

end;

As you can see the Pchar simply boldly starts at ARRAY INDEX ZERO !

OUCH

Bye,
  Skybuck.


Quantcast