Sams Teach Yourself C in 21 Days

(singke) #1
Pointers: Beyond the Basics 397

15


The second function,printarray_2(), takes a different approach. It too is passed a
pointer to an array of four integers, but, in addition, it is passed an integer variable that
specifies the number of elements (the number of arrays of four integers) that the multidi-
mensional array contains. With a single call from line 31,printarray_2()displays the
entire contents of multi.
Both functions use pointer notation to step through the individual integers in the array.
The notation (int *)ptrin both functions (lines 43 and 54) might not be clear. The
(int *)is a typecast, which temporarily changes the variable’s data type from its
declared data type to a new one. The typecast is required when assigning the value of
ptrtopbecause they are pointers to different types (pis a pointer to type int, whereas
ptris a pointer to an array of four integers). C doesn’t let you assign the value of one
pointer to a pointer of a different type. The typecast tells the compiler, “For this state-
ment only, treat ptras a pointer to type int.” Day 20, “Working with Memory,” covers
typecasts in more detail.

DOremember to use the double indirec-
tion operator (**) when declaring a
pointer to a pointer.
DOremember that a pointer increments
by the size of the pointer’s type (usually
what is being pointed to).

DON’Tforget to use parentheses when
declaring pointers to arrays.
To declare a pointer to an array of char-
acters, use this format:
char (*letters)[26];
To declare an array of pointers to charac-
ters, use this format:
char *letters[26];

DO DON’T


Working with Arrays of Pointers ........................................................................


Recall from Day 8, “Using Numeric Arrays,” that an array is a collection of data storage
locations that have the same data type and are referred to by the same name. Because
pointers are one of C’s data types, you can declare and use arrays of pointers. This type
of program construct can be very powerful in certain situations.
Perhaps the most common use of an array of pointers is with strings. A string, as you
learned on Day 10, “Working with Characters and Strings,” is a sequence of characters
stored in memory. The start of the string is indicated by a pointer to the first character (a
pointer to type char), and the end of the string is marked by a null character. By declar-
ing and initializing an array of pointers to type char, you can access and manipulate a
large number of strings using the pointer array. Each element in the array points to a dif-
ferent string, and by looping through the array, you can access each of them in turn.

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

Free download pdf