Owen Winter
Owen Winter

Reputation: 65

How to simplify creating an unpopulated array of integers

How do I create an array of x integers without creating / defining the x integers. This example will create a 10 integer array (pre-populated with zeros in each element):

 var
   IntArray : TArray<Integer>;
 begin
   IntArray := TArray<Integer>.Create(0,0,0,0,0,0,0,0,0,0);
 end;

So I created an array of integers that is 120 integers long, which started to look messy:

IntA := TArray<Integer>.Create(
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0);

And now I need to create an array of 9000 integers, and I don't need (or want) to pre-populate the array with 9000 zeros.

Is there a command like:

IntA := TArray<Integer>.Array[0..9000]; //This doesn't work

Thanks.

Upvotes: 2

Views: 161

Answers (1)

David Heffernan
David Heffernan

Reputation: 613252

Use SetLength:

SetLength(IntA, N);

where N is the length of the array you wish to allocate.

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. For multidimensional dynamic arrays, SetLength may take more than one-length parameter (up to the number of array dimensions).

Upvotes: 7

Related Questions