Skip to content

Instantly share code, notes, and snippets.

@radiofreejohn
Created March 12, 2011 22:56
Show Gist options
  • Save radiofreejohn/867662 to your computer and use it in GitHub Desktop.
Save radiofreejohn/867662 to your computer and use it in GitHub Desktop.
K&R exercise 5-4, strend, find string at end of another string
#include <stdio.h>
int strend(char *s, char *t);
int strend(char *s, char *t)
{
//save pointer to the first element of t
char *start = t;
//move to the end of each string
while (*++s)
;
while (*++t)
;
//compare from end to beginning
while (t > start && *--t == *--s)
;
return start == t;
}
int main()
{
char ape[] = "what spam";
char baboon[] = "what spam";
char chimp[] = "spam";
char lemur[] = "eggs";
int what;
what = strend(ape, baboon);
printf("%s at end of %s? %d\n",baboon, ape, what);
what = strend(ape, chimp);
printf("%s at end of %s? %d\n",chimp, ape, what);
what = strend(ape, lemur);
printf("%s at end of %s? %d\n",lemur, ape, what);
return 0;
}
@radiofreejohn
Copy link
Author

// This is buggy, does not match if a == b... hmmm

Fixed now. The loop (*--t == *--s) would continue before the start of the character array and by chance (or not) would always return 0 for a certain while so that it under-ran the start variable.

Actually this could be made more optimal if I compared t with start rather than *t and *s > 0.

Even better, do the comparison to start first, then it will stop the underflow, and remove the need for t++ before the return.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment