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!

2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Options 2 and 4 seem most likely to suit

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.