How to pass a multidimensional array to a function in C and C++

This code will not work in either C or C++. An array of type int[4][4] is not convertible to a pointer of type int ** (which is what int *arr[] stands for in parameter declaration). If you managed to compile it in C, it is simply because you probably ignored a C compiler warning of basically the same format as the error message you got from C++ compiler. (Sometimes C compilers issue warnings for what is essentially an error.)

So, again, don’t make assertions that are not true. This code does not work in C. In order to convert a built-in 2D array into a int ** pointer you can use a technique like this one

Converting multidimensional arrays to pointers in c++

(See the accepted answer. The problem is exactly the same.)

EDIT: The code appears to work in C because another bug in the printing code is masquerading the effects of the bug in array passing. In order to properly access an element of an int ** pseudo-array, you have to use expression *(*(arr + i) + j), or better a plain arr[i][j] (which is the same thing). You missed the extra * which made it print something that has absolutely nothing to do with the content of your array. Again, initialize your array in main to something else to see that the results you are printing in C have absolutely nothing to do with the your intended content of the array.

If you change the printf statement as shown above, your code will most likely crash because of the array-passing bug I described initially.

One more time: you cannot pass a int[4][4] array as an int ** pseudo-array. This is what the C++ is telling you in the error message. And, I’m sure, this is what your C compiler told you, but you probably ignored it, since it was “just a warning”.

Leave a Comment