Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C > K&R2 , section ...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 1 of 3 Topic 25427 of 27670
Post > Topic >>

K&R2 , section 5.4

by arnuld <arnVuld@[EMAIL PROTECTED] > Apr 8, 2008 at 02:34 PM

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.
 




 3 Posts in Topic:
K&R2 , section 5.4
arnuld <arnVuld@[EMAIL  2008-04-08 14:34:38 
Re: K&R2 , section 5.4
Irrwahn Grausewitz <ir  2008-04-08 11:52:05 
Re: K&R2 , section 5.4
Philip Potter <pgp@[EM  2008-04-08 11:14:22 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Fri Oct 10 22:02:51 CDT 2008.