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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With