Search code examples
delphidelphi-2010

String to Char Array using a for loop string[0] is always null


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.


Solution

  • 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;