views:

202

answers:

2

Hello all,
I have a dynamic array. But initially I am not knowing the length of the array. Can I do like first I set the length of it as 1 and then increase length as I needed without lost of previously stored data?
I know I can do such task using TList. But I want to know whether I can do it with array or not?

+10  A: 

Dynamic Arrays can be resized to a larger size without losing the contained data.

The following program demonstrates this in action.

program Project7;

{$APPTYPE CONSOLE}

uses
  SysUtils;
var
 A : Array of Integer;
 I : Integer;
begin
  for I := 0 to 19 do
  begin
    SetLength(A,I+1);
    A[I] := I;
  end;
  for I := Low(A) to High(A) do
  begin
    writeln(A[I]);
  end;
  readln;
end.
Robert Love
Just be aware it can be a memory intensive operation, because the whole array could be moved if there is not enough space to extend it where it is allocated. An array, unlike lists, must be allocated in a contiguos memory block. That's why list (and other containers) exist. Use the best container for you needs.
ldsandon
@ldsandon: Be careful: Many "lists" in Delphi are implemented as arrays or at least contiguous memory blocks in exactly the same way as an array "under the hood". TList, TObjectList, TStringList... these most commonly encountered lists are all effectively arrays inside object wrappers. The "Length" of these "arrays" has more flexible management tools than "real" arrays however, as they support both Capacity (size of the "array") and Count (number of elements actually being used) so you can pre-allocate the contiguous memory you need (via Capacity) before filling it.
Deltics
One point of clarification that you may already know. I don't know if any of this optimization would matter on modern-day machines, but the example above calls SetLength() for *every* new element. As Idsandon's comment notes, SetLength can be memory intensive. If that's the case, then calling SetLength() less often might be faster. For example, you could call it once every 100 (or even 1000) elements. Of course, you'd have to track when you need to call it:if (Length(A) < (I + 1) then SetLength(A, I + 100);
Robert Frank
Deltics: I was not speaking of TList. That's just a simple implementation of a list which internally uses an array, although at least it can take care of arrays larger than the number of used elemets. But there are better list implementations - and Delphi containers really need improvements.
ldsandon
+3  A: 

Have a look at this question:

How to implement dynamic arrays in Delphi

Jørn E. Angeltveit