Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I resize a Delphi array without losing its previous contents?

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?

like image 271
Himadri Avatar asked Jul 06 '10 06:07

Himadri


People also ask

Can array sizes be changed?

The simple answer is that you cannot do this. Once an array has been created, its size cannot be changed. Instead, an array can only be "resized" by creating a new array with the appropriate size and copying the elements from the existing array to the new one.

Which method is used to modify the size of the array?

Resize(T[], Int32) Method is used to resize the number of elements present in the array. Or in other words, this method is used to change the number of elements of a one-dimensional array to the specified new size. It resizes the only 1-D array, not multidimensional array.

Can you change the size of an array while the program is running?

If you create an array by initializing its values directly, the size will be the number of elements in it. Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array.


1 Answers

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.
like image 101
Robert Love Avatar answered Sep 23 '22 02:09

Robert Love