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

Your email address will not be published. Required fields are marked *

You May Also Like

Delphi Compiler Error E2313 Attribute – Known attribute cannot specify properties Reason for the Error & Solution No further information...
Delphi Compiler Error E2379 Virtual methods not allowed in record types Reason for the Error & Solution No further information...
Rodrigo , one of the long time Delphi Developer has been working on one of his personal project “Delphi IDE...