14

I'd like to know how to set the length of multidimensional arrays/create dynamic multidimensional arrays in Pascal. Like SetLength(arr,len) does for one dimensional arrays. I cannot find the answer.

Olli
  • 1,231
  • 15
  • 31
Jonathan
  • 141
  • 1
  • 1
  • 3
  • 1
    One could argue that pascal doesn't support multi dimensional dynamic arrays, but only dynamic arrays of dynamic arrays. – CodesInChaos Apr 03 '11 at 16:47
  • 4
    Not '*only* dynamic arrays of dynamic arrays' but also dynamic arrays of dynamic arrays of dynamic arrays, as well as dynamic arrays of dynamic arrays of dynamic arrays of dynamic arrays, and also... er... well, frankly, 'multi-dimensional dynamic arrays' seems much shorter. :) – Andriy M Apr 03 '11 at 17:29

1 Answers1

23
var
  arr: array of array of real;

...

SetLength(arr, 10, 20); // creates a 10 by 20 matrix

A bad, but equivalent, way of doing this is to do

SetLength(arr, 10);
for i := low(arr) to high(arr) do
  SetLength(arr[i], 20);

The latter approach allows "non-rectangular" arrays, however.

Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384
  • Works properly under Free Pascal/Lazarus! – matandked Feb 11 '17 at 21:17
  • Why is the second way "bad"? I guess it will generate multiple memory allocations and also unnecessarily copy content, that only contains 0. Is that correct? – dummzeuch Jan 09 '20 at 11:20
  • @dummzeuch: I know this is a very old question, but I wanted to clarify that both the first and second approaches really are equivalent, as stated in the answer. They both generate the same number of memory allocations of the same size and even in the same order. The only difference is that in the first example SetLength is doing the looping while in the second example (the "bad" example) the example code is doing the looping. – davidmw May 22 '20 at 13:03