Today I got a task to convert as C# desktop application into a Delphi XE application. One thing I learned is about dynamic multidimensional array. In C#, we can do this by just simply using one-liner “new” command and state the array dimension with it. As in Delphi, this is not the case, since all variables had to be declared far-before used.
Dynamic multidimensional array in Delphi can be declared using iterated “array of” keyword
1 2 | var myInt: array of array of Integer; |
Inside “begin“..”end” of a procedure/function that using the array, we can determine or change the array dimension like this:
1 | SetLength(myInt, 3, 3); |
That command will set myInt into 3×3 dimension array. Apparently, Delphi also allowed you to have a multidimensional array that has different number of column for each row, for example:
1 2 3 | SetLength(myInt, 2); SetLength(myInt[0], 3); SetLength(myInt[1], 2); |
The first row will made myInt array have 2 rows without specifying how may columns. Second line will set the first row to have 3 columns and third line will set the second row of myInt to have 2 columns.
To check how many row or column a multidimensional array had, you can use “Length” command
1 2 | Length(myInt); //this will return number of rows from a multidimensional array Length(myInt[0]); //how many columns does first row of myInt had |
Destroying a dynamic multidimensional array can be done by assigning the array to nil
1 | myInt:=nil; |
You can’t use dynamic multidimensional array as procedure/function parameter or result type directly. You’ll get error if you do this:
1 2 3 4 | function foo(myInt: array of array of Integer): array of array of Integer; begin //do something end; |
Instead of that, you had to define your own variable type and until then you can use it as function parameter or result type.
1 2 3 4 | interface type TMyInt: array of array of Integer; |
Using your own variable type in function:
1 2 3 4 | function foo(myInt: TMyInt): TMyInt; begin //do something end; |
Important Notes: if you work on 2 dimensional array that related to object that had table (such as stringgrid) or image/bitmap coordinate, you had to switch the term “row” and “column” I described above. Delphi use this: table_name[column, row];.