This is exercise 5-4 from K&R. I spent hours tweaking it but now it seems to work. I'm new to pointers and I'd welcome any comments about how to do it better.
/* Function strend(s, t), which returns 1 if the string t
* occurs at the end of string s and zero otherwise */
int strend(const char *s, const char *t)
{
const char *s0, *t0;
if (s == 0) {
printf("s is NULL pointer\n");
return (-1);
}
if (t == 0) {
printf("t is NULL pointer\n");
return (-1);
}
s0 = s;
t0 = t;
while (*s++)
;
s -= 2; /* *s points to last real char in s */
while (*t++)
;
t -= 2; /* *t points to last real char in t */
if ((t-t0) > (s-s0))
return (0); /* t is longer than s */
while (t>=t0) {
if (*s-- != *t--)
return (0); /* Mismatch */
}
return (1); /* Match */
}
Here is main()
:
/* Test the function strend(s, t), which returns 1 if the string t
* occurs at the end of string s and zero otherwise */
#include "jim.h"
#include "subs.c"
char a[MAXLINE], b[MAXLINE];
int main (void)
{
printf("Return = %1d, Expect = 1\n", strend("12345", "45"));
printf("Return = %1d, Expect = 0\n", strend("12345", "35"));
printf("Return = %1d, Expect = 0\n", strend("45", "345"));
printf("Return = %1d, Expect = 1\n", strend("12345", "12345"));
printf("Return = %1d, Expect = 1\n", strend("12345", "5"));
printf("Return = %1d, Expect = 0\n", strend("12345", "4"));
printf("Return = %1d, Expect = 1\n", strend("12345", ""));
printf("Return = %1d, Expect = 0\n", strend("12345", "+"));
printf("Return = %1d, Expect = 0\n", strend("12345", "a2345"));
printf("Return = %1d, Expect = 1\n", strend("", ""));
printf("Return = %1d, Expect = 0\n", strend("", "Z"));
printf("Return = %1d, Expect = 1\n", strend("1", "1"));
printf("Return = %1d, Expect = 0\n", strend("1", "1A"));
printf("Return = %1d, Expect = -1\n", strend(0, "1A"));
printf("Return = %1d, Expect = -1\n", strend("1", 0));
}
Here is the output:
Return = 1, Expect = 1 Return = 0, Expect = 0 Return = 0, Expect = 0 Return = 1, Expect = 1 Return = 1, Expect = 1 Return = 0, Expect = 0 Return = 1, Expect = 1 Return = 0, Expect = 0 Return = 0, Expect = 0 Return = 1, Expect = 1 Return = 0, Expect = 0 Return = 1, Expect = 1 Return = 0, Expect = 0 s is NULL pointer Return = -1, Expect = -1 t is NULL pointer Return = -1, Expect = -1