When passing a 2-dimensional array to a function in C, I normally just pass it by using a single pointer.
Example : void process_array(int* arr, int rows, int cols)
I see 2-dimensional arrays also passed as below with only the number of elements of the 2nd dimension (if it is known).
I can't understand what is the advantage of it being passed in this way. For example below, how does it benefit the compiler by stating the size of the second dimension only? Just by telling it that we have an array (unknown size) of arrays of ints with a known size of 3.
#include <stdio.h>
#include <stdlib.h>
void process_array(int arr[][3], int rows, int cols)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
int main()
{
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
process_array(matrix, 3, 3);
return 0;
}
When passing a 2-dimensional array to a function in C, I normally just pass it by using a single pointer.
Example :
void process_array(int* arr, int rows, int cols)
If, by this, you mean that the called routine accesses the array as a one-dimensional array, then that technically has undefined behavior in the C standard. (However, compilers may support it.)
For example below, how does it benefit the compiler by stating the size of the second dimension only?
When the array is accessed properly, as a two-dimensional array, the compiler needs to know the size of the second dimension so that it can calculate where the elements are.
Suppose we are passed a multidimensional array that contains 12 int
in total. Let’s number the int
in memory as 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, and 11, although we will not access them with these indices in source code.
Clearly arr[0][0]
is element 0, and arr[0][1]
is element 1 if it exists. Where is arr[1][0]
? If the original matrix is defined with int matrix[4][3]
, then arr[1][0]
is element 3. however, if the original matrix is defined with int matrix[3][4]
, then arr[1][0]
is element 4. In general, arr[i][j]
is element i*s + j
, where s
is the number of elements in the second dimension. So the compiler needs to know the size of the second dimension in order to calculate where an element is.
The compiler does not need to know the first dimension to calculate i*s + j
. As long as you use a valid i
, which is your job, the formula i*s + j
will locate element arr[i][j]
. The compiler would only need the size of the first dimension if it needed to calculate the size of the entire array or to locate the end of the entire array.