Pascal - Dynamic Arrays

Advertisements


In case of a dynamic array type, the initial length of the array is zero. The actual length of the array must be set with the standard SetLength function, which will allocate the necessary memory for storing the array elements.

Declaring Dynamic Arrays

For declaring dynamic arrays you do not mention the array range. For example:

type  
   darray = array of integer;
var
   a: darray;

Before using the array, you must declare the size using the setlength function:

setlength(a,100);

Now, the array a has a valid array index range from 0 to 999: the array index is always zero-based.

The following example declares and uses a two dimensional dynamic array:

program exDynarray; 
var
   a: array of array of integer; (* a 2 dimensional array *)
   i, j : integer;  
begin  
   setlength(a,5,5);  
   for i:=0 to 4 do  
      for j:=0 to 4 do  
         a[i,j]:= i * j;  
   for i:=0 to 4 do  
   begin  
      for j:= 0 to 4 do  
      write(a[i,j]:2,' ');  
    writeln;  
   end;  
end.

When the above code is compiled and executed, it produces the following result:

0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12
0 4 8 12 16


Advertisements
Advertisements