Recent

Author Topic: Dynamic array question  (Read 735 times)

user5

  • Sr. Member
  • ****
  • Posts: 357
Dynamic array question
« on: July 11, 2020, 02:04:35 pm »
Does the code below look okay and will Button13Click return the memory used by the array?

Code: Pascal  [Select][+][-]
  1. type
  2.   companions = array of string;
  3.   grouper = array of companions;
  4.  
  5. var
  6.  box:grouper;
  7.  
  8. procedure TForm1.Button10Click(Sender: TObject);
  9. var i:integer;
  10. begin
  11.  //Create the array and initial all elements to 'x'
  12.  //box := grouper.create;  //Is this needed?
  13.  setlength(box,10000,10);
  14.  for i := 0 to 9999 do
  15.   begin
  16.    box[i][0] := 'x';
  17.    box[i][1] := 'x';
  18.    box[i][2] := 'x';
  19.    box[i][3] := 'x';
  20.    box[i][4] := 'x';
  21.    box[i][5] := 'x';
  22.    box[i][6] := 'x';
  23.    box[i][7] := 'x';
  24.    box[i][8] := 'x';
  25.    box[i][9] := 'x';
  26.   end;
  27. end;
  28.  
  29. procedure TForm1.Button13Click(Sender: TObject);
  30. begin
  31.  setlength(box,0,0);
  32. end;

jamie

  • Hero Member
  • *****
  • Posts: 6090
Re: Dynamic array question
« Reply #1 on: July 11, 2020, 02:14:02 pm »
looks good to me..
The only true wisdom is knowing you know nothing

PascalDragon

  • Hero Member
  • *****
  • Posts: 5446
  • Compiler Developer
Re: Dynamic array question
« Reply #2 on: July 11, 2020, 02:36:16 pm »
Does the code below look okay and will Button13Click return the memory used by the array?

As you're only using simple types (in contrast to pointers or class instances), yes, the code in Button13Click will free all the memory (at least if noone else has a reference to your array).

Warfley

  • Hero Member
  • *****
  • Posts: 1499
Re: Dynamic array question
« Reply #3 on: July 11, 2020, 03:00:21 pm »
SetLength(box, 0) would already be enough, or even shorter, box := nil;

PascalDragon

  • Hero Member
  • *****
  • Posts: 5446
  • Compiler Developer
Re: Dynamic array question
« Reply #4 on: July 11, 2020, 05:37:35 pm »
SetLength(box, 0) would already be enough, or even shorter, box := nil;

True.

 

TinyPortal © 2005-2018