How to create a procedure like SetLength, which also has zeros in memory?

In some cases, I need to set the size of a dynamic array, and then fill it with zeros.

Sort of:

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) will not compile.

+4
source share
1 answer

Read the Embarcadero documentation :

procedure SetLength(var S: <string or dynamic array>; NewLength: Integer);

For a dynamic array variable, SetLength redistributes the array referenced by S to the specified length. Existing elements in the array are saved, and the newly allocated space is set to 0 or zero.

This means that SetLength- that’s all you want.


, , SetLength NewLength = 0 .

:

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;
+14

Source: https://habr.com/ru/post/1657284/


All Articles