Domanda

I have 2 2-dimensional arrays and a function.

I would like that function to take the array as an argument.

I tried code like this:

var array1:array[1..10,1..10] of integer;
    array2:array[1..20,1..10] of integer;
function name(var my_array:array of array of integer, n:integer);
function name(var my_array:array[1..n,1..10] of integer;const n:integer);

But I got errors while trying to compile the code. Any tips?

If you would like me to paste error codes for each version please leave a comment with a request.

For

function name(var my_array:array of array of integer, n:integer);

The error code is: "Incompatible type for arg no. : Got "Array[0..10] of Array[0..10] of SmallInt", expected "Open array od SmallInt" every time I call the function.

È stato utile?

Soluzione

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.

Altri suggerimenti

You shuld use a new type in these situations . like the following:

Type
     vector = array [1..20,1..20] of integer;
var array1:vector;
array2:vector;
function name(var my_array:vector, n:integer);
function name(var my_array:vector;const n:integer);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top