CCS C Software and Maintenance Offers
FAQFAQ   FAQForum Help   FAQOfficial CCS Support   SearchSearch  RegisterRegister 

ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

CCS does not monitor this forum on a regular basis.

Please do not post bug Reports on this forum. Send them to support@ccsinfo.com

Problem in function strncmp ()

 
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion
View previous topic :: View next topic  
Author Message
qwwe



Joined: 17 Sep 2017
Posts: 53

View user's profile Send private message

Problem in function strncmp ()
PostPosted: Sat Oct 07, 2017 10:29 am     Reply with quote

Hi this code in the library string.h

Code:

signed int8 strncmp(unsigned char *s1, unsigned char *s2, size_t n)
{
   for (; n > 0; s1++, s2++, n--)
      if (*s1 != *s2)
         return((*s1 <*s2) ? -1: 1);
      else if (*s1 == '\0')
         return(0);
 [color=red] return(0);[/color]
}


What does the red part do?
Ttelmah



Joined: 11 Mar 2010
Posts: 12523

View user's profile Send private message

PostPosted: Sat Oct 07, 2017 11:59 am     Reply with quote

It returns 0 if the strings match to the length of str1.

The standard definition for strncmp is:

Quote:

This function return values that are as follows −

if Return value < 0 then it indicates str1 is less than str2.

if Return value > 0 then it indicates str2 is less than str1.

if Return value = 0 then it indicates str1 is equal to str2.


The first 'return' handles the top two situations. Returning the < and > situations.
The second return handles the situation that the strings match till you get to the end of the first string.
The line you are pointing to handles the situation where the strings match for the entire count.

This is the 'correct' exit. Hardly a problem....

What is wrong?. The commonest problem is getting the two pointers the wrong way round. If (for instance) you are searching for the word "TEST", then this needs to be passed as the first string (str1). Otherwise if you pass it as the second, "T", "TE", "TES", will all be accepted, since you will hit the end of the first string while still matching.
Display posts from previous:   
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group