Sams Teach Yourself C in 21 Days

(singke) #1
Pointers: Beyond the Basics 399

15



  • It initializes message[0]to point to the first character of the string “one”,
    message[1]to point to the first character of the string “two”, andmessage[2]to
    point to the first character of the string “three”.
    This is illustrated in Figure 15.4, which shows the relationship between the array of
    pointers and the strings. Note that in this example, the array elements message[3]
    throughmessage[9]aren’t initialized to point at anything.


FIGURE15.4
An array of pointers to
typechar.

message[0]
message[1]
message[2]
message[3]
message[4]
message[5]
message[6]
message[7]
message[8]
message[9]

1000
1556
2012
???????

1000

1556

2012

one\0

two\0

three\0

Now look at Listing 15.5, which is an example of using an array of pointers.

LISTING15.5 message.c. Initializing and using an array of pointers to type
char
1: /* Initializing an array of pointers to type char. */
2:
3: #include <stdio.h>
4:
5: int main( void )
6: {
7: char *message[8] = { “Four”, “score”, “and”, “seven”,
8: “years”, “ago,”, “our”, “forefathers” };
9: int count;
10:
11: for (count = 0; count < 8; count++)
12: printf(“%s “, message[count]);
13: printf(“\n”);
14:
15: return 0;
16: }

Four score and seven years ago, our forefathers
This program declares an array of eight pointers to type charand initializes them
to point to eight strings (lines 7 and 8). It then uses a forloop on lines 11 and 12
to display each element of the array on-screen.

INPUT

OUTPUT

ANALYSIS

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

Free download pdf