We have already looked at one-dimensional arrays. They provide a means of
accessing many instances of a single datatype using only one identifier. In C,
we can declare arrays to be of almost any dimension.
The only thing tricky about multidimensional arrays crops up when you pass them
as arguments to functions. Otherwise, as long as you can think in more than
one dimension, you should have no problem.
It is easy to visualize a two-dimensional array as a table. Take a
look at ``marray1.c'' in your ``examples'' directory (or
view it directly). We have declared a 9x9 array which we fill
up with the multiplication table. After we have filled it up, we
print it out. Just as for loops are handy for dealing with
one-dimensional arrays, doubly-nested for loops are handy for
dealing with two-dimensional arrays.
What's a good way of visualizing a three-dimensional array?
Click here for the answer
Take a look at ``marray2.c'' (or view it directly).
The main program declares and constructs a three-dimensional array called
``tables''. It is then filled in so that it contains an addition table, a
subtraction table, and a multiplication table. (Note the three sets of
doubly-nested for loops.)
Now take a look at the print_table function. It prints out a 9x9
arithmetic table. What kind of array argument does it expect?
Click here for the answer
Now notice how we pass it three different two-dimensional arrays to print. We
index ``tables'' only with the first index, which essentially ``peels
off'' a two-dimensional array which we then pass as a two-dimensional argument.
This is an example of how multi-dimensional arrays can be decomposed into
lower-dimensional arrays.
If you're observant, you'll be wondering why we had to declare the exact bounds
of the two-dimensional argument to print_table, since we don't have to
declare the bounds of one-dimensional array arguments. Actually, we
don't have to declare all of the bounds of a two-dimensional array.
Try modifying the implementation of print_table so that the declaration
of table reads
char table[][9]
Now try compiling the program. It should compile OK.
Try modifying the implementation of print_table one more time so that
the declaration of table reads
char table[][]
Try compiling it again. What happens?
Click here for an answer
You might be wondering what happens if you make a mistake in declaring the
bounds of a multi-dimensional array used as a function parameter. Try it out.
Change the declaration of ``table'' in print_table to read
char table[][7]
Compile and run the program. What happens?
Hamlet Project
hamlet@cs.utah.edu