2

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • I just wonder why use generics here? – Anton Duzenko Feb 11 '17 at 11:21
  • 1
    You should always use the generic form of the dynamic array because it offers compatibility with other generic code. Exception to that is if you have to support older compilers without generics. – David Heffernan Feb 11 '17 at 11:29
  • 2
    @AntonDuzenko, generic dynamic arrays has relaxed type identity rules. See [What are the reasons to use TArray instead of Array of T?](http://stackoverflow.com/q/14383093/576719). – LU RD Feb 11 '17 at 11:30

1 Answers1

7

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).

LU RD
  • 34,438
  • 5
  • 88
  • 296
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490