Home > other >  If the code is correct, why do I get a range check error?
If the code is correct, why do I get a range check error?

Time:07-22

unit Unit1;

interface

uses
  System.Classes, Vcl.Controls, Winapi.Messages, System.SysUtils, System.Variants, Vcl.Graphics,
  Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,System.StrUtils;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  i:integer;
  Cnt:integer;
  s:string;
begin
  Cnt := 0;
  s := Edit1.Text;
  for i := 0 to Length(s) do
    if s[i] =  '.' then
       Cnt := Cnt   1;
  ShowMessage(IntToStr(Cnt));
end;

end.

After executing the code as above, if I try to find out how many there are,a Range Check Error occurs.

I was checking the example questions. I wonder if there is a problem with the code?

The example is using one TEdit and I was going to make it using one TButton.

CodePudding user response:

Problem is here:

for i := 0 to Length(s) do

because of some reasons:

string characters are numerated from 1 to Length(s), so valid indices for the string of length 3 are s[1], s[2], s[3], and your call to s[0] causes range check error.

Delphi/Pascal for loop includes both lower and upper range values, so this code tries to make Length(s) 1 runs instead of Length(s)

Instances of UnicodeString can index characters. Indexing is 1-based, just as for AnsiString., same refers to other string types except for PChar family.

(There is also rarely used compiler option {$ZEROBASEDSTRINGS})

  • Related