Solution for Exercise 19-12
ex1912
#include <stdio.h>
int main()
{
char sample[] = "From whence cometh my help?\n";
char *ps = sample;
while(*ps != '\0')
{
putchar(*ps);
ps++;
}
return(0);
}
Notes
* Unlike Listing 19-6 in the book, you don't need the index variable to make the code work; the ps pointer itself acts as an index.
* In Line 6 the pointer variable ps is created and assigned the address of the string variable sample.
* A while loop is used to work through the string, similar to the code in Listing 19-6. The while loop could have been written to use the index variable, in which case it could look like this:
The while loop as written in my solution (top) is cleaner.
*Refer to Table 19-2 (in the book) if you need a review on the *(a+n) format, but that defeats the purpose; the pointer itself is the index you can use to march through a string.
* The while loop's statements could theoretically be combined into a single statement:
Grant yourself extra For Dummies bonus points if you came up with that solution.
* By the way, the putchar(*ps++); construction is still possible by using array notation, but it's terrifically ugly.
Copyright © 1997-2025 by QPBC.
All rights reserved
