You need to declare your own type, and then use that type as the parameter to your function. Instead of passing the array dimensions, use the Low
and High
functions from the System
unit; they will work with both static (pre-declared) and dynamic arrays, and avoid hard-coding array sizes and iterators.
You want to avoid hard-coding integer indexes, becaue static arrays in Pascal don't have to start with index 0
; the following is a perfectly legal Pascal array declaration, where the array bounds are from index -3
to 3
:
var
Arr: array[-3..3] of Integer;
Here's an example using a dynamic array (array of array of Integer
) that loops through the two dimensional array and sums the values; it initializes a 5 x 5 array, populates it with data, and then calls the SumTwoDimIntArray
function to sum the values.
program Project2;
{$APPTYPE CONSOLE}
uses
SysUtils;
type
TTwoDimIntArray = array of array of Integer;
function SumTwoDimIntArray(Arr: TTwoDimIntArray): Integer;
var
i, j: Integer;
begin
Result := 0;
for i := Low(Arr) to High(Arr) do
for j := Low(Arr[i]) to High(Arr[i]) do
Result := Result + Arr[i][j];
end;
var
MyArr: TTwoDimIntArray;
i, j: Integer;
begin
SetLength(MyArr, 5);
for i := Low(MyArr) to High(MyArr) do
begin
SetLength(MyArr[i], 5);
for j := Low(MyArr[i]) to High(MyArr[i]) do
MyArr[i][j] := j + 1;
end;
WriteLn(Format('Sum is %d', [SumTwoDimIntArray(MyArr)]));
ReadLn;
end.