Here is an example of a program that reads a matrix and a vector,
multiplies the vector by the matrix and writes the answer. It
includes a subroutine call for a subroutine that does the
multiplication.

MAX
. Then there is the working size. This is
determined by the user at run time and kept in the variables m
and n
. They must both be less than or equal
to MAX
. The remaining allocated rows and columns are
unused.
The matrix is passed to the subroutine in the same way that we pass singly subscripted arrays (vectors). In this example the function declaration specifies the complete allocated dimension of the matrix and vectors. Doubly subscripted matrices in C and C++ are stored by rows. So the 50 x 50 matrix is stored as follows:
a[0][0] a[0][1] ... a[0][49] a[1][0] a[1][1] ... a[49][0] ... a[49][49]with the second subscript varying most rapidly. The compiler needs to know the allocated number of columns in the matrix in order to be able to find the beginning of each row, starting from the first element
a[0][0]
. The allocated number of columns is the second
number in the declaration double a[MAX][MAX];
. The
compiler actually ignores the first dimension in the declaration of
each formal argument. So we can safely drop the first subscript
dimension if we like and write it as
void matmul(int n, double a[][MAX], double x[], double b[]){or equivalently as
void matmul(int n, double a[][MAX], double *x, double *b){However, the compiler signals an error if we omit the second dimension in
a[][MAX]
.
Here, the identifier a
is technically a pointer to the
first element of the array. And a[i]
(and curiously,
also a + i
) is a pointer to the first element of the i
th row.