1
procedure TfmCypher.btn1Click(Sender: TObject);
var
  i: integer;
 MasterkeyArray: array of char;
 Masterkey : string;
 j : integer;
begin
Masterkey := edtKey.text;
setlength(MasterKeyArray, length(edtkey.text));

for i:= 0 to length(masterkey) do
begin
 MasterkeyArray[i] := masterkey[i];
end;

In the above code, I am trying to figure out why MasterKeyArray fills as { #0, a, b} MasterKeyArray is always #0. Ultimately I just want a charArray of my string masterkey. I kept having issues with masterkey[0] being assigned #0. Masterkey string is collected from an editbox.text.

1 Answer 1

4

Strings are 1-indexed, but arrays are 0-indexed. Your loop is trying to access string index 0, which is not valid, and you are exceeding the upper bound of the array as well.

Try this instead:

procedure TfmCypher.btn1Click(Sender: TObject);
var
  i: integer;
  MasterkeyArray: array of Char;
  Masterkey : string;
begin
  Masterkey := edtKey.text;
  SetLength(MasterKeyArray, Length(Masterkey));

  for I := 1 to Length(MasterKey) do
  begin
    MasterkeyArray[I-1] := Masterkey[I];
  end;
end;

A simplier solution is to get rid of the loop altogether and use Move() instead:

procedure TfmCypher.btn1Click(Sender: TObject);
var
  i: integer;
  MasterkeyArray: array of Char;
  Masterkey : string;
begin
  Masterkey := edtKey.text;
  SetLength(MasterKeyArray, Length(Masterkey));
  if Masterkey <> '' then begin
    Move(Masterkey[1], MasterKeyArray[0], Length(Masterkey) * SizeOf(Char));
  end;
end;
Sign up to request clarification or add additional context in comments.

3 Comments

Awesome thank you! can you tell me a bit more about why this is the case with strings?
@user1868232: Backward compatibility. Pascal strings (ShortString, or String[255]) stored their length in byte 0, and the first character of the string in byte 1. When long strings were introduced in Delphi 2, they remained 1-based for compatibility with older code and have stayed that way ever since.
Until XE3, that is, when the {$ZEROBASEDSTRINGS} directive was added to optionally enable 0-based string indexing. It is OFF by default, but may be turned ON in the future when the new mobile environment is ready.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.