|
|
View previous topic :: View next topic |
Author |
Message |
qwwe
Joined: 17 Sep 2017 Posts: 59
|
Problem in function strncmp () |
Posted: Sat Oct 07, 2017 10:29 am |
|
|
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: 19552
|
|
Posted: Sat Oct 07, 2017 11:59 am |
|
|
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. |
|
|
|
|
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
|