9

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?

1
  • Did you read the documentation about dynamic arrays? Which part of it did you not understand? Commented Jul 6, 2010 at 15:34

1 Answer 1

16

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.
Sign up to request clarification or add additional context in comments.

4 Comments

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: 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.
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);
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.