Solution for Exercise 19-18

ex1918

#include <stdio.h>

int main()
{
    char *fruit[] = {
        "watermelon",
        "banana",
        "pear",
        "apple",
        "coconut",
        "grape",
        "blueberry"
    };
    int x;

    for(x=0;x<7;x++)
        puts(*(fruit+x));

    return(0);
}

Notes

* Line 17 (the puts() function) works because the fruit array contains pointers. Each element is a memory location, specifically the address of a string. So fruit+0 is the first element in the array, and *(fruit+0) is the address of a string. Therefore that variable can be used to represent a string anywhere in the code as a string.

* In a way, this code is merely the pointer notation version of Exercise 19-17. The fruit[x] notation is changed to *(fruit+x), which is described in the book's Table 19-2.