Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strncmp implementation

Tags:

c

string

compare

I have the following implementation of strncmp function with a test driver, however that does`t compile.

I`m also not sure if the logic is correct. Here is the error message from my compiler:

warning: control may reach end of non-void function [-Wreturn-type]

#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;
 }
like image 286
user 004325 Avatar asked Apr 11 '26 04:04

user 004325


1 Answers

Aside from errors mentioned by others, you are supposed to compare the characters as unsigned char. This gets important once you go beyond ASCII-7, your results will be wrong if you don't.

The following is my own (tested) implementation (from my original work on PDCLib, which is CC0 licensed).

int strncmp( const char * s1, const char * s2, size_t n )
{
    while ( n && *s1 && ( *s1 == *s2 ) )
    {
        ++s1;
        ++s2;
        --n;
    }
    if ( n == 0 )
    {
        return 0;
    }
    else
    {
        return ( *(unsigned char *)s1 - *(unsigned char *)s2 );
    }
}
like image 150
DevSolar Avatar answered Apr 12 '26 18:04

DevSolar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!