Sams Teach Yourself C in 21 Days

(singke) #1
printf(“%d”, multi[0][0]);
printf(“%d”, *multi[0]);
printf(“%d”, **multi);
These concepts apply equally to arrays with three or more dimensions. Thus, a three-
dimensional array is an array with elements that are each a two-dimensional array; each
of these elements is itself an array of one-dimensional arrays.
This material on multidimensional arrays and pointers might seem a bit confusing. When
you work with multidimensional arrays, keep this point in mind: An array with ndimen-
sions has elements that are arrays with n-1 dimensions. When nbecomes 1, that array’s
elements are variables of the data type specified at the beginning of the array declaration
line.
So far, you’ve been using array names that are pointer constants and that can’t be
changed. How would you declare a pointer variable that points to an element of a multi-
dimensional array? Look at the previous example, which declared a two-dimensional
array as follows:
int multi[2][4];
To declare a pointer variable ptrthat can point to an element of multi(that is, can point
to a four-element integer array), you write
int (*ptr)[4];
You then make ptrpoint to the first element of multiby writing
ptr = multi;
You might wonder why the parentheses are necessary in the pointer declaration. Brackets
([]) have a higher precedence than *. If you wrote
int *ptr[4];
you would be declaring an array of four pointers to type int. Indeed, you can declare
and use arrays of pointers. This isn’t what you want to do now, however.
How can you use pointers to elements of multidimensional arrays? As with single-dimen-
sional arrays, pointers must be used to pass an array to a function. This is illustrated for a
multidimensional array in Listing 15.4, which uses two methods of passing a multidi-
mensional array to a function.

LISTING15.4 ptrmulti.c. Passing a multidimensional array to a function
using a pointer
1: /* Demonstrates passing a pointer to a multidimensional */
2: /* array to a function. */
3:

394 Day 15

INPUT

25 448201x-CH15 8/13/02 11:13 AM Page 394

Free download pdf