Programming in C

(Barry) #1
Functions and Arrays 147

An entire multidimensional array can be passed to a function in the same way that a
single-dimensional array can:You simply list the name of the array. For example, if the
matrix measured_valuesis declared to be a two-dimensional array of integers, the C
statement


scalarMultiply (measured_values, constant);


can be used to invoke a function that multiplies each element in the matrix by the value
of constant.This implies, of course, that the function itself can change the values con-
tained inside the measured_valuesarray.The discussion of this topic for single-
dimensional arrays also applies here: An assignment made to any element of the formal
parameter array inside the function makes a permanent change to the array that was
passed to the function.
When declaring a single-dimensional array as a formal parameter inside a function,
you learned that the actual dimension of the array is not needed; simply use a pair of
empty brackets to inform the C compiler that the parameter is, in fact, an array.This
does not totally apply in the case of multidimensional arrays. For a two-dimensional
array, the number of rows in the array can be omitted, but the declaration mustcontain
the number of columns in the array. So the declarations


int array_values[100][50]


and


int array_values[][50]


are both valid declarations for a formal parameter array called array_valuescontaining
100 rows by 50 columns; but the declarations


int array_values[100][]


and


int array_values[][]


are not because the number of columns in the array mustbe specified.
In Program 8.13, you define a function scalarMultiply, which multiplies a two-
dimensional integer array by a scalar integer value. Assume for purposes of this example
that the array is dimensioned 3 x 5.The mainroutine calls the scalarMultiplyroutine
twice. After each call, the array is passed to the displayMatrixroutine to display the
contents of the array. Pay careful attention to the nested forloops that are used in both
scalarMultiplyand displayMatrixto sequence through each element of the two-
dimensional array.


Program 8.13 Using Multidimensional Arrays and Functions


#include <stdio.h>


int main (void)
{

Free download pdf