Exercise 5-4. Write the function
strend(s,t), which returns 1 if the stringtoccurs at the end of the strings, and zero otherwise.
Advance both pointers to their respective null terminators, then walk backwards together comparing characters. If t runs out first (pointer reaches the start of t), every character matched — t is a suffix of s. If s runs out first, s is shorter than t and the answer is no.
Solution
/* K&R Exercise 5-4 — strend: does t occur at the end of s?
* Compile: gcc -ansi -Wall ex5-4.c -o ex5-4 */
#include <stdio.h>
int strend(const char *s, const char *t)
{
const char *ps = s, *pt = t;
while (*ps) ps++; /* advance to end of s */
while (*pt) pt++; /* advance to end of t */
/* Walk backwards together while characters match */
while (pt > t && ps > s && *--ps == *--pt)
;
return *ps == *pt && pt == t;
}
int main(void)
{
printf("%d\n", strend("hello world", "world")); /* 1 */
printf("%d\n", strend("hello world", "hello")); /* 0 */
printf("%d\n", strend("hello", "hello")); /* 1 */
printf("%d\n", strend("hello", "")); /* 1 — empty string */
printf("%d\n", strend("hi", "hello")); /* 0 — t longer than s */
printf("%d\n", strend("", "")); /* 1 */
return 0;
}
Why the Final Test Is pt == t
When the loop exits, either:
pt == t— all oftwas matched; return 1 if the last compared characters also matched (*ps == *pt)ps == s— ran out ofsbefore exhaustingt;tis longer thans, return 0- Characters differed — return 0
The condition *ps == *pt && pt == t handles all three cases correctly, including the empty string edge case (both pointers at their respective starts with matching null terminators).
Compile and Run
gcc -ansi -Wall ex5-4.c -o ex5-4 && ./ex5-4
Sample Output
1 0 1 1 0 1
What This Exercise Teaches
- Pointer comparison for bounds checking —
pt > tandps > sdetect when a pointer has walked back to the start; pointer comparison within the same array is well-defined - Walking backwards — advance to end, then decrement; a common pattern for suffix/palindrome problems
- Empty string edge case — every string ends with the empty string; the condition handles this naturally because both pointers start and end at
t
Set Up Your C Environment
← Exercise 5-3 |
Chapter 5 Solutions |
Exercise 5-5 →
Book: The C Programming Language, 2nd Ed — Kernighan & Ritchie