K&R2, exercise 5.4



PURPOSE: see comments or the problem statement from the K&R2
GETTING: 1 as the only output :(


/* Exercise 5.4 from K&R2, page 107
*
* write the function strend(s, t) which returns 1 if the
* striing t occurs at the end of string s and zero otherwise
*
*/


#include <stdio.h>
#include <stdlib.h>

int strend( char*, char* );


/* main() will only call the function to do the necessary work. */
int main()
{
int arrsize_s, arrsize_t, arrdiff;
char *ps, *pt;
char s[] = "Like a Stone";
char t[] = "Stone";

arrsize_s = (int) sizeof(s) / sizeof(char);
arrsize_t = (int) sizeof(t) / sizeof(char);
arrdiff = arrsize_s - arrsize_t - 1;

/* we will start at the position in the 1st array, of same length as of
2nd array,
* so that we can compare from there till end. anything before that
length is * of no use to us.
*
*/
ps = s + arrdiff;
pt = t;

printf("\n%d\n", strend(ps,pt));


return EXIT_SUCCESS;
}


/* I amu sing pointers because, arrays are never passed to functions and I
* don't want to FAKE the array call
* outer for loop checks for each element of 1st array. * inner for loop
compares elements of both arrays. * if condition checks whether we have
compared the 2nd array till end. */
int strend( char* s, char* t )
{
char *pj;

for( ; *s != '\0'; *s++ )
{
printf("s --> %c\n--------------------\n\n", *s);
for( pj = s; *t == *pj; t++, pj++ )
{
printf("*t --> %c\n", *t);
printf("*pj --> %c\n", *pj);
}

if( *t == '\0' )
{
return 1;
}
}

return 0;
}



--
http://lispmachine.wordpress.com/

Please remove capital 'V's when you reply to me via e-mail.

.



Relevant Pages

  • Re: K&R2, exercise 5.4
    ... int strend(char*, char*); ... outer for loop checks for each element of 1st array. ... inner for loop compares elements of both arrays. ... int strend(char* s, char* t) ...
    (comp.lang.c)
  • Re: K&R2, exercise 5.4
    ... that has a bug:(, this is the newer version free of bugs. ... int strend(char*, char*); ... outer for loop checks for each element of 1st array. ... int strend(char* s, char* t) ...
    (comp.lang.c)
  • Re: Is the following code OK?
    ... can we compare two pointers that are pointing to the ... > char * ptr; ... Any object can be viewed as an array of characters. ...
    (comp.lang.c)
  • Re: sentinel
    ... > were the same char. ... type in the string "end" and for your loop to break at that point. ... end is a char variable, stname is an array of twelve chars, This means they ... but you cannot compare an array for equality with anything. ...
    (comp.lang.cpp)
  • string comparison
    ... type is "array of char". ... How can we compare two different objects for equality? ... which conversion rule from C standard is applied here? ...
    (comp.lang.c)