Recent

Author Topic: TStringList to Array  (Read 4138 times)

BubikolRamios

  • Sr. Member
  • ****
  • Posts: 267
TStringList to Array
« on: July 29, 2016, 07:24:00 am »
Code: Pascal  [Select][+][-]
  1. var
  2.   sa:TStringList;
  3.   sb:Array of TStringList;
  4.   i: integer;
  5. begin
  6.   sa := TStringList.Create;
  7.   sa.Clear;
  8.   sa.Add('1');
  9.   sa.Add('2');
  10.   SetLength(sb,Length(sb)+1);
  11.   sb[0] := sa;
  12.   SynEdit1.Lines.add(sb[0].Text);
  13.  
  14.   sa.Clear;
  15.   sa.Add('3');
  16.   sa.Add('4');
  17.   SetLength(sb,Length(sb)+1);
  18.   sb[1] :=  sa;
  19.   SynEdit1.Lines.add(sb[1].Text);
  20.  
  21.   for i := 0 to Length(sb)-1 do
  22.   begin
  23.        SynEdit1.Lines.add(sb[i].Text);
  24.   end;    
  25.  

Out:
12
34
34
34

What happens in loop ?  Last two outputs are expected to be
12
34

« Last Edit: July 29, 2016, 07:34:49 am by BubikolRamios »
lazarus 3.2-fpc-3.2.2-win32/win64

molly

  • Hero Member
  • *****
  • Posts: 2330
Re: TStringList to Array
« Reply #1 on: July 29, 2016, 07:41:03 am »
You create one stringlist
Code: [Select]
6.  sa := TStringList.Create;

Then you add values to it:
Code: [Select]
7.  sa.Add('1');
8.  sa.Add('2');

then you set the length of the array:
Code: [Select]
9.  SetLength(sb,Length(sb)+1);

you set the first entry of the array to sa
Code: [Select]
10. sb[0] := sa;

then you clear that same sa stringlist (all values cleared from that list):
Code: [Select]
11.  sa.Clear;

then you add two values to sa:
Code: [Select]
12. sa.Add('3');
13. sa.Add('4');

then you 'expand' the array again to make room for...
Code: [Select]
14.  SetLength(sb,Length(sb)+1);

... yet another entry of the same sa stringlist class.
Code: [Select]
15.   sb[1] :=  sa;

1. Storing a stringlist into an array does not automagically creates a copy for you
2. Using the same reference to the same stringlist means that you are still manipulating that same stringlist (and thus its contents).

PS: you changed the code so my analyses does not match your code accurately anymore.
« Last Edit: July 29, 2016, 07:43:24 am by molly »

BubikolRamios

  • Sr. Member
  • ****
  • Posts: 267
Re: TStringList to Array
« Reply #2 on: July 29, 2016, 07:44:57 am »
Yeah, changed a bit, important thing in changed is this:
Code: Pascal  [Select][+][-]
  1. SynEdit1.Lines.add(sb[0].Text);
  2. SynEdit1.Lines.add(sb[1].Text);
  3. for i := 0 to Length(sb)-1 do
  4. begin
  5.        SynEdit1.Lines.add(sb[i].Text);
  6. end;
  7.  

out:
12
34
34
34

So, it looks like the stuff is there, before loop, inside sb
and then in loop it is not there any more.

Quote
Using the same reference to the same stringlist means that you are still manipulating that same stringlist (and thus its contents).

OK, got it.
Thanks.
« Last Edit: July 29, 2016, 07:47:27 am by BubikolRamios »
lazarus 3.2-fpc-3.2.2-win32/win64

 

TinyPortal © 2005-2018