3

I'd like to pass a multi-dimensional array to a constructor like so:

constructor TMyClass.Create(MyParameter: array of array of Integer);
begin
  LocalField := MyParameter;
end;

Where LocalField is an array of array of Integer.

However the above code won't compile ('Identifier expected but ARRAY found'). Could somebody explain to me why this is wrong? I tried reading up on open, static and dynamic arrays but have yet to find something that works. Is there a way to fix it without changing the type of LocalField?

4 Answers 4

16

Make a specific type for localfield, then set that as the type of MyParameter, something along the lines of:

type
  TTheArray = array[1..5] of array[1..10] of Integer;

var
  LocalField: TTheArray;

constructor TMyClass.Create(MyParameter: TTheArray);
...

(Note: not verified in a compiler, minor errors may be present)

Note that most often in pascal-like syntax a multidimensional array is more properly declared as

type
  TTheArray = array[1..5, 1..10] of Integer;

Unless, of course, you have some good reason for doing it the other way.

0
1

I don't have Delphi at hands, but I think this should work:

type
  TIntArray = array of Integer;

...

constructor TMyClass.Create (MyParameter : array of TIntArray);
begin
...
end;
1

If a type is used before as suggested in the answer, please note that you are passing it as a reference, see:

https://blog.spreendigital.de/2016/08/01/pass-a-multidimensional-array-as-a-parameter-with-a-hidden-caveat/

0

I prefer this

procedure MakeMat(var c: TMatrix; nr, nc: integer; a: array of double);
var
  i, j: integer;
begin
  SetLength(c, nr, nc);
  for i := 0 to nr-1 do
    for j := 0 to nc-1 do
      c[i,j] := a[i*nc + j];
end;


MakeMat(ya, 5, 11,
       [1.53,1.38,1.29,1.18,1.06,1.00,1.00,1.06,1.12,1.16,1.18,
        0.57,0.52,0.48,0.44,0.40,0.39,0.39,0.40,0.42,0.43,0.44,
        0.27,0.25,0.23,0.21,0.19,0.18,0.18,0.19,0.20,0.21,0.21,
        0.22,0.20,0.19,0.17,0.15,0.14,0.14,0.15,0.16,0.17,0.17,
        0.20,0.18,0.16,0.15,0.14,0.13,0.13,0.14,0.14,0.15,0.15]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.