Pass a multidimensional array as a parameter (with a hidden caveat)

Monday, August 1st, 2016 | Dennis D. Spreen | Delphi Programming

How to pass a multidimensional array as a parameter? Long ago this question was answered on Stack Overflow with a simple answer: make a specific type for your array. But there is a hidden caveat…

If you need to pass a multidimensional array as a parameter you’d probably type this

however the above code won’t compile (‘E2029 Identifier expected but ARRAY found’). By declaring a specific type for the array it compiles:

Looks nice, but there is something nasty hidden in there. But let’s take a step back – how about changing your one dimensional array procedures the same way? Your procedure may look like

but surely is a lot better to read by declaring an integer array type before:

Are both the same? No, they aren’t. Let’s prove it with a little bit of more code:

At first a dynamic array with a size of 1 is created and before the two Inc’s are called it is filled with 1 – as both procedures uses the array passed as a value, both lines should still read “1” afterwards. But the second memo line shows a “6 – this call is a call by reference!

Adding a const or var doesn’t change anything – the dynamic array is always passed as a reference if declared as a type!

What about the nextgen (iOS/Android) compiler? It’s the same, so be careful by replacing dynamic array parameters by array types – you always end up passing them by reference!




4 Comments to Pass a multidimensional array as a parameter (with a hidden caveat)

Rudy Velhuis
August 3, 2016

These are not “dynamic array parameters”, they are “open array parameters”. You cannot only pass dynamic arrays to them, you can just as well pass static arrays or open array constructors. Do not confuse them with dynamic arrays. More in my article “Open array parameters and array of const”, ( That also explains why “array of” parameter declarations are not dynamic arrays.

Dynamic arrays are reference types, that is why you can update their values, just like you can change properties if an object is passed into a function.

August 4, 2016

@rudy: You wrote in part “Confusion”:
“procedure OnlyDyn(Arr: TMonthArray) will only accept dynamic arrays, so you can use SetLength here (this will however use a copy, and not change the original array”
But that’s not true – the dynamic array isn’t used a copy – it’s passed as reference (see my example above)!
And yes, I may a bit confused about open and dynamic arrays, thank you for your great article.
…. hmm ok sorry, you wrote “if setlength is used *then* it uses a copy” ..

Dennis D. Spreen
August 4, 2016

looks like I have to rewrite my article a little bit 😉

August 11, 2016


Leave a comment

About Dennis D. Spreen

I'm an avid programmer working on a variety of platforms in a variety of languages with a wide technical interest.


QR Code