In some cases I need to set size of a dynamic array and then fill it with zeros.
Something like:
procedure SetLengthAndZero(VAR X; NewSize: Integer);
begin
SetLength(x, newsize);
if newsize > 0
then FillChar(x[0], length(x)* SizeOf(x[0]), 0);
end;
But the code above (obviously) won't compile.
In Delphi 7, the content of the memory is undefined after SetLength.
Read Embarcadero's documentation:
procedure SetLength(var S: <string or dynamic array>; NewLength: Integer);For a dynamic array variable, SetLength reallocates the array referenced by S to the given length. Existing elements in the array are preserved and newly allocated space is set to 0 or nil.
This means that SetLength is all you want.
If you want to clear the whole dynamic array, not just allocate more items and preserve existing items, just call SetLengthwith NewLength = 0 before calling it again with the wanted length.
A generic solution:
Type
TDynArrayTool = record
class procedure ClearAndSetLength<T>( var arr : TArray<T>; newLen : Integer); static;
end;
class procedure TDynArrayTool.ClearAndSetLength<T>(var arr: TArray<T>;
newLen: Integer);
begin
Setlength(arr,0);
SetLength(arr,newLen);
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