Failed to set TStringLists array in Delphi

Var
  i : Integer;
  j : Integer;
  oSLArray : array of TStringList;
  oSL : TStringList;
begin
  SetLength(oSLArray, emailPassword.Lines.Count);
  for i := 0 to emailPassword.Lines.Count - 1 do
    {oSLArray[i] := TStringList.Create;
    oSLArray[i].Delimiter := ' ';
    oSLArray[i].DelimitedText := emailPassword.Lines[i];
    for j := 0 to oSLArray[i].Count-1 do begin
      Showmessage( oSLArray[i].Strings[j] );
    end; }
    oSL := TStringList.Create;
    oSL.Delimiter := ' ';
    oSL.DelimitedText := emailPassword.Lines[i];
    for j := 0 to oSL.Count-1 do begin
      Showmessage( oSL[j] );
    end;
  end;

I am trying to create an array of TStringLists, read that from RichEdit 'EmailPassword', and then print it (I will put it into the array when I get to this).

When I uncomment oSLarray, I get an access violation. When I tried it using oSL, nothing printed.

Now I understand that an access violation means that the pointer may be incorrectly set, since I think that the access violation occurs in oSLArray [i]: = TStringList.Create.

Did I just miss something small?

+5
source share
2 answers

I adjusted the code, I believe that this code will work, but I only tested it in my head.

var 
  i : Integer; 
  j : Integer; 
  oSLArray : array of TStringList; 
  oSL : TStringList; 
begin
  if not(Assigned(emailpassword)) then exit;
  SetLength(oSLArray, emailPassword.Lines.Count); 
  for i := 0 to emailPassword.Lines.Count - 1 do begin
    oSLArray[i] := TStringList.Create; 
    oSLArray[i].Delimiter := ' '; 
    oSLArray[i].DelimitedText := emailPassword.Lines[i]; 
    for j := 0 to oSLArray[i].Count-1 do begin 
      Showmessage( oSLArray[i].Strings[j] );   <<--- The error has here
    end; {for j} 
  end; {for i}

    //oSL := TStringList.Create; 
    //try
    //  oSL.Delimiter := ' '; 
    //  oSL.DelimitedText := emailPassword.Lines[i]; 
    //  for j := 0 to oSL.Count-1 do begin 
    //    Showmessage( oSL[j] ); 
    //  end; {for j}
    //finally
    //  oSL.Free;
    //end; {try}
    //end; {for i} 
end;

:

for i := 0 to emailPassword.Lines.Count - 1 do //don't forget begin
  oSLArray[i] := TStringList.Create; 
  oSLArray[i].Delimiter := ' '; 
  oSLArray[i].DelimitedText := emailPassword.Lines[i]; 
//<<<--  Here for i loop should end, but it does not.
    for j := 0 to oSLArray[i].Count-1 do begin 
 //You loop though all members of OSLArtray, even though only the first item is set, 
 //the rest is unassigned.
      Showmessage( oSLArray[i].Strings[j] );  <<-- Access Violation 
    end; } 
+7

/ . ,

for i := 0 to emailPassword.Lines.Count - 1 do

oSLArray[i] := TStringList.Create;

oSLArray[i].Delimiter := ' '; 

.

+4

All Articles