开发者

Having trouble setting array of TStringLists in Delphi

Var
  i : Integer;
  j : Integer;
  oSLArray : array of TStringList;
  oSL : TStringList;
begin
  SetLength(oSLArray, emailPassword.Lines.Count);
  for i := 0 to emailPassword.L开发者_运维问答ines.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'm trying to make an array of TStringLists, read what's coming from the RichEdit 'EmailPassword', and then print it (I will put it in an array when I get that far).

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

Now, I understand an access violation means the pointer may not be set properly, as I think the access violation is occurring at oSLArray[i] := TStringList.Create.

Am I just missing something small?


I've corrected the code, I believe this code will work, but I've 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;

Here's your old code with comments:

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


The absence of a begin/end pair is the problem. Without the comments, the

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

loop iterates only the line

oSLArray[i] := TStringList.Create;

the line

oSLArray[i].Delimiter := ' '; 

is executed after the loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜