We have rectangular multi-dimensional arrays in C, though they are generally less used than arrays of pointers. Let’s look at the following function for matrix multiplication:
#define MAXROWS 10 #define MAXCOLS 10 /* This calculates the product of two matrices: * mat1 which is an m x n matrix * mat2 which is an n x p matrix * product = mat1 x mat2 * product will be an m x p matrix. */ void matmul(int mat1[MAXROWS][MAXCOLS], int mat2[MAXROWS][MAXCOLS], int product[MAXROWS][MAXCOLS], int m, int n, int p) { int i, j, k; for (i = 0; i < m; i++) { for (j = 0; j < p; j++) { product[i][j] = 0; for (k = 0; k < n; k++) { product[i][j] += mat1[i][k] * mat2[k][j]; } } } }
The formal argument of matmul
int mat1[MAXROWS][MAXCOLS]
represents a two-dimensional array. in C, a two-dimensional array is a one-dimensional array, each of whose elements is an array. Hence, subscripts are written as:
mat1[i][j]
Elements are stored by rows, so the rightmost subscript (or column) varies fastest as elements are accessed in storage order. We could use the following function to print the matrix used above:
void print_matrix(int mat[MAXROWS][MAXCOLS], int rows, int cols) { int i, j; for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) printf("%d ", mat[i][j]); printf("\n"); } }
In the above function declaration, we can skip MAXROWS, since the number of rows is irrelevant:
void print_matrix(int mat[][MAXCOLS], int rows, int cols) { ... }
We could also declare the function like this:
void print_matrix(int (*mat)[MAXCOLS], int rows, int cols) { ... }
which says the parameter is a pointer to an array of MAXCOLS integers. The parentheses are necessary since brackets [] have a higher precedence than *.
The declaration:
int *mat[MAXCOLS]
is an array of MAXCOLS pointers to integers.
So, only the first dimension(subscript) of an array is free; all the others have to be specified.