Solution for Exercise 19-11

ex1911

#include <stdio.h>

int main()
{
    float temps[5] = { 58.7, 62.8, 65.0, 63.3, 63.2 };

    printf("The temperature on Tuesday will be %.1f\n",
            *(temps+1));
    printf("The temperature on Friday will be %.1f\n",
            *(temps+4));
    return(0);
}

Notes

* Above you see the literal solution to the problem: Array notation was replaced with pointer notation, but I used the same variable name. That may have thrown you for a loop. It works, but it may not be what you were expecting. Instead, consider this following code as a valid, alternative solution:

#include <stdio.h>

int main()
{
    float temps[5] = { 58.7, 62.8, 65.0, 63.3, 63.2 };
    float *t;

    t = temps;
    printf("The temperature on Tuesday will be %.1f\n",
            *(t+1));
    printf("The temperature on Friday will be %.1f\n",
            *(t+4));
    return(0);
}

* A pointer variable t is declared at Line 6.

* Line 8 initializes the pointer.

* I've split the two printf() statements so that the pointer notation part is on at line by itself, similar to the way that Listing 19-5 is presented in the book.

* In Line 10, t+1 references the second element of the array. The first element would be t+0 or just t by itself. The element must be enclosed in parentheses (per Table 19-2) so that pointer arithmetic references the proper array element. The * outside of the parentheses then gathers the value stored at that location, ditto for *(t+4) at Line 12.