Sams Teach Yourself C in 21 Days

(singke) #1
Pointers: Beyond the Basics 391

15


Remember that the name of an array without brackets is a pointer to the first array ele-
ment. The term multi[0]is the name of the array multi[0][0]with the last pair of
brackets missing, so it qualifies as a pointer.
If you’re a bit confused at this point, don’t worry. This material is difficult to grasp. It
might help if you remember the following rules for any array of ndimensions used in
code:


  • The array name followed by npairs of brackets (each pair containing an appropri-
    ate index, of course) evaluates as array data (that is, the data stored in the specified
    array element).

  • The array name followed by fewer than npairs of brackets evaluates as a pointer to
    an array element.
    In the example, therefore,multievaluates as a pointer,multi[0]evaluates as a pointer,
    andmulti[0][0]evaluates as array data.
    Now look at what all these pointers actually point to. Listing 15.1 declares a two-dimen-
    sional array—similar to those you’ve been using in the examples—and then prints the
    values of the associated pointers. It also prints the address of the first array element.


LISTING15.1 multi.c. The relationship between a multidimensional array
and pointers
1: /* Demonstrates pointers and multidimensional arrays. */
2:
3: #include <stdio.h>
4:
5: int multi[2][4];
6:
7: int main( void )
8: {
9: printf(“\nmulti = %u”, multi);
10: printf(“\nmulti[0] = %u”, multi[0]);
11: printf(“\n&multi[0][0] = %u\n”, &multi[0][0]);
12:
13: return 0;
14: }

multi = 4206592
multi[0] = 4206592
&multi[0][0] = 4206592
The actual value might not be 4206592 on your system, but all three values will
be the same. The address of the array multiis the same as the address of the
arraymulti[0], and both are equal to the address of the first integer in the array,
multi[0][0].

INPUT

OUTPUT

ANALYSIS

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

Free download pdf