2

I have a very simple code snippet which you can check here:

type
  TMatrix = array of array of Byte;
  PMatrix = ^TMatrix;

const
testarray:array [0..2,0..2] of Byte=(
(1,2,3), (4,5,6), (7,8,9));

function PickValue(input:PMatrix):Byte;
begin
  Result:=input^[1,3];
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Showmessage(inttostr(PickValue(@testarray)));
end;

end.

How can I cast testarray properly to pass it to the PickValue function? Above code crashes in its current form. I'm using delphi 2007.

Thanks in advance!

LU RD
  • 34,438
  • 5
  • 88
  • 296
unknown1
  • 23
  • 2
  • Does it help if you index testarray as 1..3,1..3? I do not see why you should need to, but maybe that will give some reader a clue? – Jeremy Kahan Nov 06 '16 at 13:39
  • See also [Passing Static arrays as parameters for Dynamic arrays in Delphi](http://stackoverflow.com/q/1593535/576719). – LU RD Nov 06 '16 at 13:49

1 Answers1

7

You cannot cast that static array to be a dynamic array. These types are simply not compatible. The static array is laid out in one contiguous block of memory. The dynamic array has indirection to variable sized arrays at each dimension. In effect think of it as ^^Byte with extra compiler management and meta data. No amount of casting can help you.

You have, at least, the following options:

  1. Copy the contents of the static array to a dynamic array. Then pass that dynamic array to your function.
  2. Switch your static array to be a dynamic array so that no conversion is needed.
  3. Arrange that your function accepts static arrays rather than dynamic arrays, again to avoid requiring a conversion.
  4. Have the function accept a pointer to the first element and the inner dimension. Then perform the indexing manually. The i,j element is at linear offset i*innerDim + j.

Your pointer type PMatrix is probably not needed. Dynamic arrays are already implemented as pointers. This seems to be a level of indirection too far.

Of course, asking for element 3 when the array indices only go up to 2 isn't right, but that is presently the lesser of your concerns. Remember that dynamic arrays are zero based and you have specified zero based for your static array.

I am struggling to be able to recommend which solution is best since I don't understand your real goals and usage based on the simplified example presented here.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Basically i'd like to pass 2 2dimension arrays to the function, but the size of the dimensions are different. The first matrix is 0..15,0..15 dimensions, while the second one is 0..4,0..4. – unknown1 Nov 06 '16 at 17:06
  • Options 2 and 4 seem most likely to suit – David Heffernan Nov 06 '16 at 17:47