150 Chapter 8 Working with Functions
The scalarMultiplyfunction is called a second time to multiply the now modified
elements of the sampleMatrixarray by –1.The modified array is then displayed by a
final call to the displayMatrixfunction, and program execution is then complete.
Multidimensional Variable-Length Arrays and Functions
You can take advantage of the variable-length array feature in the C language and write
functions that can take multidimensional arrays of varying sizes. For example, Program
8.13 can been rewritten so that the scalarMultiplyand displayMatrixfunctions can
accept matrices containing any number of rows and columns, which can be passed as
arguments to the functions. See Program 8.13A.
Program 8.13A Multidimensional Variable-Length Arrays
#include <stdio.h>
int main (void)
{
void scalarMultiply (int nRows, int nCols,
int matrix[nRows][nCols], int scalar);
void displayMatrix (int nRows, int nCols, int matrix[nRows][nCols]);
int sampleMatrix[3][5] =
{
{ 7, 16, 55, 13, 12 },
{ 12, 10, 52, 0, 7 },
{ -2, 1, 2, 4, 9 }
};
printf ("Original matrix:\n");
displayMatrix (3, 5, sampleMatrix);
scalarMultiply (3, 5, sampleMatrix, 2);
printf ("\nMultiplied by 2:\n");
displayMatrix (3, 5, sampleMatrix);
scalarMultiply (3, 5, sampleMatrix, -1);
printf ("\nThen multiplied by -1:\n");
displayMatrix (3, 5, sampleMatrix);
return 0;
}
// Function to multiply a matrix by a scalar
void scalarMultiply (int nRows, int nCols,
int matrix[nRows][nCols], int scalar)