Solution for Exercise 19-12
#include <stdio.h>
int main()
{
char sample[] = "From whence cometh my help?\n";
char *ps;
ps = sample; /* initialize the pointer */
while(*ps != '\0')
{
putchar(*ps);
ps++;
}
return(0);
}
Output
From whence cometh my help?
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. At Line 8, it's assigned the address of string sample
.
* A while loop works 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:
*Refer to Table 19-2 (in the book) if you need a review on the *(a+n)
format, but this approach defeats the purpose; the pointer itself is the index you can use to march through a string.
* One problem with incrementing the pointer (done in Line 13) is that the base address is lost. To re-work through the string, you must re-initialize pointer ps
to the sample
array.
Copyright © 1997-2024 by QPBC.
All rights reserved