Thread: Strncmp implementation help

  1. #1
    Registered User
    Join Date
    Aug 2015
    Posts
    69

    Strncmp implementation help

    Description:

    Compare at most n characters of string cs to string ct; return<0 if cs<ct, 0 if cs == ct or >0 if cs>ct.


    Code:
    #include <stdio.h>
    #include <string.h>
    
    
    #undef strncmp
    
    
    
    
    int strncmp(const char *s, const char *t, size_t n)
    	
    {
    	
    	int i;
    	
    	do
    	  {
    		for (i = 0; s[i] == t[i]; i++)
    	
    		  if (s[i] == 0)
    			  return 0;
    	
    	      return s[i] - t[i];
    	  }
    	  
          while (--n > 0);
     }
    
    
    
    
    
    
     int main ()
     {
       char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
       int n;
       puts ("Looking for R2 astromech droids...");
       for (n=0 ; n<3 ; n++)
         if (strncmp (str[n],"R2xx",2) == 0)
         {
           printf ("found %s\n",str[n]);
         }
       return 0;
     }


    Does not work.

  2. #2
    Tweaking master Aslaville's Avatar
    Join Date
    Sep 2012
    Location
    Rogueport
    Posts
    528
    In your code, I didn't see you test for equality of characters anywhere ,...

    Edit: Ooh, saw it

  3. #3
    Ticked and off
    Join Date
    Oct 2011
    Location
    La-la land
    Posts
    1,728
    Quote Originally Posted by coder222 View Post
    Code:
    	do
    	  {
    	      for (i = 0; s[i] == t[i]; i++)
    
    	          if (s[i] == 0)
    	              return 0;
    
    	      return s[i] - t[i];
    	  }
    	while (--n > 0);
    You have two loops nested.

    Innermost for loop compares the two strings, from beginning to end, disregarding any length limit (n).

    Outer loop decreases the length limit, repeating as long as the length limit is positive.

    Obviously, this is not what you want. How did you intend this to work?

    (And no, the problem description is not what I'm asking. I'm asking, how did you envision your solution to work? Broken down to step by step.)
    Last edited by Nominal Animal; 09-10-2015 at 11:15 AM.

  4. #4
    Registered User
    Join Date
    May 2010
    Posts
    4,596
    What is the purpose of your do/while loop?

    You may want to examine the value being returned from the function, with the data given the function is not returning zero.

    You really shouldn't name your function the same as the standard function you're trying to emulate. And remember the standard function returns one of three values, zero, less than zero, greater than zero.

    Outer loop decreases the length limit, repeating as long as the length limit is positive.
    But that really doesn't matter because the outer loop is not actually doing anything useful, and it only executes once, because of the return statement.

    Jim
    Last edited by jimblumberg; 09-10-2015 at 11:27 AM.

  5. #5
    Ticked and off
    Join Date
    Oct 2011
    Location
    La-la land
    Posts
    1,728
    Quote Originally Posted by jimblumberg View Post
    But that really doesn't matter because the outer loop is not actually doing anything useful, and it only executes once, because of the return statement.
    Jim's absolutely right.



    Whenever you write some code, you should always check that the code does what you intended.

    In the beginning, it is very hard, because you're concentrating on the problem statement. It does get easier in time.

    When you learn to read code -- and this is often much easier than writing code -- you learn to decipher what the code actually does. (You'll also notice that best comments are those that describe the programmer intent, or the assumptions and requirements the code has. Comments that describe what the code does are completely useless, just annoying.)

    The trick is to "switch" your mind from the "writing stance" to the "reading stance", and read the code you've written as if it was written by someone else. Then, you can compare what you intended to what the code actually does. When you pinpoint the divergences -- like the inner loop end/return condition in the original code -- it is fairly simple to correct the issues.

    It is often easier to rewrite code, rather than fix it. Of course, you don't want to rewrite everything from scratch, as that'd be wasteful. Here, you only need to rewrite the innards of the function, really. In some other cases, just rewriting a loop, or a part of a function, or in the other direction, a file that contains functions used by other files, works best. The idea is much the same as in woodworking: If you can fix it with a bit of glue, okay. You might be able to fix it with a small patch. But, if the problem is that the member is rotten to the core, moldy, or twisted beyond repair, you yank it out, and replace with a new one.

  6. #6
    Registered User
    Join Date
    Aug 2015
    Posts
    69
    Innermost for loop compares the two strings, from beginning to end, disregarding any length limit (n).
    I didn`t know that.

    My current code is as follows:

    Code:
    #include <stdio.h>
    #include <string.h>
    
    
    #undef strncmp
    
    
    
    
    int strncmp(const char *s, const char *t, size_t num)
    
    
    
    
      	
    {
    	
    	 for ( ; num >0; s++, t++, num--)
    	
    		  if (*s == 0)
    			  return 0;
    	
    	      return *s - *t;
    }
    	  
     
    
    
    
    
    
    
     int main ()
     {
       char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
       int n;
       puts ("Looking for R2 astromech droids...");
       for (n=0 ; n<3 ; n++)
         if (strncmp (str[n],"R2xx",2) == 0)
         {
           printf ("found %s\n",str[n]);
         }
       return 0;
     }

    It does' t work.

  7. #7
    Registered User
    Join Date
    May 2010
    Posts
    4,596
    In the loop in your function where do you ever test to see the characters in both string are equal, less than, or greater than each other?

    Jim

  8. #8
    Registered User
    Join Date
    Aug 2015
    Posts
    69
    Something like this?

    Code:
    #include <stdio.h>
    #include <string.h>
    
    
    #undef strncmp
    
    
    
    
    int strncmp(const char *s, const char *t, size_t num)
    
    
    
    
      	
    {
    	
    	 for ( ; num >0;  s++, t++, num--)
    		 
    	 
    		 
              if (*s == 0)
    			  return 0;
    	 
    	      if (*s == *t)
    			  ++s;
    		      ++t;
    			    
    		   else if (*s != *t)
    	          return *s - *t;
    	      
    }
    	  
     
    
    
    
    
    
    
     int main ()
     {
       char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
       int n;
       puts ("Looking for R2 astromech droids...");
       for (n=0 ; n<3 ; n++)
         if (strncmp (str[n],"R2xx",2) == 0)
         {
           printf ("found %s\n",str[n]);
         }
       return 0;
     }

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,323
    Did you even try to compile that before asking?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,323
    Also, don't do this:
    Code:
    #undef strncmp
    You do not know if strncmp really is a macro name, and even if it is, it is reserved to the implementation, so defining your own strncmp function still results in undefined behaviour unless you are implementing the standard library. It is easy enough to come up with another name, e.g., coder222_strncmp.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. question about strncmp
    By sweetorangepie in forum C Programming
    Replies: 8
    Last Post: 03-24-2008, 01:15 PM
  2. strncmp
    By TL62 in forum C Programming
    Replies: 9
    Last Post: 01-16-2008, 05:12 PM
  3. strncmp like function in C#
    By x77 in forum C# Programming
    Replies: 4
    Last Post: 11-18-2007, 06:29 AM
  4. Help with strncmp fxn
    By 3kgt in forum C++ Programming
    Replies: 5
    Last Post: 04-30-2003, 02:40 PM
  5. strncmp()
    By xlordt in forum C Programming
    Replies: 2
    Last Post: 10-23-2002, 01:54 PM