HomeDelphiDelphi Error – E2157 Element 0 inaccessible – use ‘Length’ or ‘SetLength’

Delphi Error – E2157 Element 0 inaccessible – use ‘Length’ or ‘SetLength’

Delphi Compiler Error

E2157 Element 0 inaccessible – use ‘Length’ or ‘SetLength’

Reason for the Error & Solution

The Delphi String type does not store the length of the string in element 0. The old method of changing, or getting, the length of a string by accessing element 0 does not work with long strings.

program Produce;

  var
    str : String;
    len : Integer;

begin
  str := 'Kojo no tsuki';
  len := str[0];
end.

Here the program is attempting to get the length of the string by directly accessing the first element. This is not legal.

program Solve;

  var
    str : String;
    len : Integer;

begin
  str := 'Kojo no tsuki';
  len := Length(str);
end.

You can use the SetLength and Length standard procedures to provide the same functionality as directly accessing the first element of the string. If hints are turned on, you will receive a warning about the value of ‘len’ not being used.

Share:

Leave a Reply

You May Also Like

Delphi Compiler Error X2421 Imported identifier ‘%s’ conflicts with ‘%s’ in ‘%s’ Reason for the Error & Solution This occurs...
Delphi Compiler Error X2367 Case of property accessor method %s.%s should be %s.%s Reason for the Error & Solution No...
Delphi Compiler Error X2269 Overriding virtual method ‘%s.%s’ has lower visibility (%s) than base class ‘%s’ (%s) Reason for the...