I have a function, which is called sometimes with regular, sometimes dynamic arrays.
If I define the function as
function_name(int[10][10] a)
and send int** as a parameter, I get a warning. Opposite, if I declare
function_name(int** a)
and send int[][] as a parameter (after casting) I cannot access to array elements inside function.
What is the correctest way?
When an array is passed to a function, it “decays” to a pointer to its first element. So, given:
In the call
f(a),ais actually&a[0], i.e., a pointer, and the type isT *(the type of&a[0]).When you have an array of arrays, the same rule applies:
adecays to a pointer again, equal to&a[0].a[0]is of type “array [5] ofT“. So,&a[0]is of type “pointer to array [5] ofT“, i.e., if you were to declare a pointerpto set equal to&a[0], you would do:Given the above, and assuming your array is declared in the calling code as
int a[10][10];, you should declare your function as:For more, see this.
There is a syntax error in
function_name(int[10][10] a)—you need to specify the array size after the “variable” name:function_name(int a[10][10]). In fact, the above is equivalent tofunction_name(int (*a)[10]), because of the “decaying” mentioned above.Edit: ah, I think I understand now. You cannot declare a function that takes both a “two dimensional” array and a pointer-to-pointer, for the reasons mentioned above (the “decaying” to pointer happens only once). A pointer to pointer may not point to contiguous data, and may have different number of elements in each “row”. An array of arrays doesn’t cannot have those properties. They are fundamentally different.