Now let's look at what happens when arrays are passed as arguments to
functions. It should not be surprising that it is possible to pass
arrays as arguments. Arrays would be not nearly so useful otherwise,
since all but the tiniest programs are composed of many functions.
It should come as no surprise that it is possible to pass an
element of an array as an argument. In fact, you already know
everything that you need to know about this aspect of and C.
Why is that?
Click here for the answer.
You can also pass entire arrays, not just individual elements, as
arguments. Just as it is useful to write functions that operate on
numbers, it is useful to write functions that operate on arrays. In
fact, the more complex the data structure, the more reasons there are
to write functions and to manipulate it!
As a example of a function that takes arrays as arguments, let's look
at the implementation of a dot product function (also in ``examples/dotprod.c'').
(The dot product of two arrays is computed by performing a pairwise
multiplication of corresponding elements.)
Here are a two things to notice:
- In the argument list for dot_product, the parameters (x,
y, and z) are declared in a special way. They look like
this:
float x[]
That looks like an array declaration without any size. In fact, that's close
to what it means. The ``x[]'' kind of declaration means x is an
array, but that its size is unknown to the C compiler.
The dot_product function itself ``knows'' how big the arrays
are however, because it receives an extra argument--size--that
tells the size of all three arrays. Generally, when you pass an array
as an argument, you'll also have to pass along its size.
- The function dot_product takes three arrays (and a
size) a parameters. It uses the array z to communicate the
result back to the main function. In C, a function cannot
return (via a return statement) an array. However, any
assignments made to an array parameter will be visible back at the
point of call.
In this case, then, after the call to dot_product in
main, the array c will contain the answer. Notice that this
trick of ``returning'' results via a parameter does not work for
other types of parameters, such as ints and floats.
Eric N. Eide
Hamlet Project
Department of Computer Science
University of Utah