Solution for Exercise 19-16

ex1916

#include <stdio.h>

int main()
{
    char *sample = "From whence cometh my help?\n";
    char *save;

    save = sample;

    while(putchar(*sample++))
        ;
    sample = save;
    puts(sample);
    return(0);
}

Notes

* To save a pointer's location, you need another pointer. That pointer is declared at Line 6.

* Line 8 initializes the save pointer to hold the address stored in the sample pointer. The & operator isn't used because it's not needed; both variables are pointers and they hold a memory location.

* If you did use the & operator, as in save=&sample, you'd be saving the address of the sample pointer variable itself, not the address stored in the variable. (I know: crazy!)

* Lines 10 and 11 display the string, munching through the sample variable. You could have easily coded the loop by using the save variable instead. In fact, most coders keep the original variable untouched and use only the spare pointer (save in this example).

* Line 12 restores the sample pointer. Once again it holds the string's base address.

* Finally, Line 13 re-displays the original string by using the address restored to the sample pointer variable.

* Here is the output:

The second line appears indented because the while loop prints the null character at the end of the string, code 0. Not every terminal displays code 0 as a space. For example, on a Macitnosh you won't see the second line indented. Also, the puts() function adds an extra blank line to the output.