A
arnuld
PURPOSE: see comments.
OUTPUT: negative integer as output even for equal strings
/* A string comparison function from K&R2
* example code from section 5.4,page 106
*
* returns +ve number , if 1st string is greater than 2nd
* return -ve number, if 2nd string is greater than 1st
* returns 0, if both are equal
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum MAXSIZE { ARR_SIZE = 1000 };
int my_strcmp( char*, char* );
int main( )
{
char s1[ARR_SIZE], s2[ARR_SIZE];
strcpy( s1, "s" );
strcpy( s2, "s" );
printf( "%s\t%s\t --> %d\n", s1, s2, my_strcmp( s1, s2 ));
return EXIT_SUCCESS;
}
int my_strcmp( char* s1, char* s2 )
{
for( ; *s1 == *s2; s1++, s2++ )
{
if( s1 == '\0' )
{
return 0;
}
}
return *s1 - *s2;
}
/*
if( *s1 > *s2 )
{
return 1;
}
else if( *s1 < *s2 )
{
return -1;
}
else
{
return 0;
}
*/
==================== OUTPUT ======================
Welcome to the Emacs shell
/home/arnuld/programs/C $ gcc -ansi -pedantic -Wall -Wextra section_5-5.c
/home/arnuld/programs/C $ ./a.out
s s --> -151
/home/arnuld/programs/C $ ./a.out
s s --> -66
/home/arnuld/programs/C $ ./a.out
s s --> -122
/home/arnuld/programs/C $ ./a.out
s s --> -193
/home/arnuld/programs/C $
-- http://lispmachine.wordpress.com/
Please remove capital 'V's when you reply to me via e-mail.
OUTPUT: negative integer as output even for equal strings
/* A string comparison function from K&R2
* example code from section 5.4,page 106
*
* returns +ve number , if 1st string is greater than 2nd
* return -ve number, if 2nd string is greater than 1st
* returns 0, if both are equal
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum MAXSIZE { ARR_SIZE = 1000 };
int my_strcmp( char*, char* );
int main( )
{
char s1[ARR_SIZE], s2[ARR_SIZE];
strcpy( s1, "s" );
strcpy( s2, "s" );
printf( "%s\t%s\t --> %d\n", s1, s2, my_strcmp( s1, s2 ));
return EXIT_SUCCESS;
}
int my_strcmp( char* s1, char* s2 )
{
for( ; *s1 == *s2; s1++, s2++ )
{
if( s1 == '\0' )
{
return 0;
}
}
return *s1 - *s2;
}
/*
if( *s1 > *s2 )
{
return 1;
}
else if( *s1 < *s2 )
{
return -1;
}
else
{
return 0;
}
*/
==================== OUTPUT ======================
Welcome to the Emacs shell
/home/arnuld/programs/C $ gcc -ansi -pedantic -Wall -Wextra section_5-5.c
/home/arnuld/programs/C $ ./a.out
s s --> -151
/home/arnuld/programs/C $ ./a.out
s s --> -66
/home/arnuld/programs/C $ ./a.out
s s --> -122
/home/arnuld/programs/C $ ./a.out
s s --> -193
/home/arnuld/programs/C $
-- http://lispmachine.wordpress.com/
Please remove capital 'V's when you reply to me via e-mail.