A
arnuld
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;
}
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;
}