Skip to main content
deleted 9 characters in body
Source Link
coderodde
  • 32.3k
  • 15
  • 79
  • 205

You don't need pointers to character pointers at all:

int str_cmp(const char* s1, const char* s2)
{
    while (*s1 != 0 && *s2 != 0'\0' && *s1 == *s2)
    {
        ++s1;
        ++s2;
    }
    
    if (*s1 == *s2)
    {
        return 0;
    }
    
    return *s1 < *s2 ? -1 : 1;
}

Also, there is a bug in your second implementation: it returns 1 on compareStrings("hello", "helloo"), when the correct result is -1.

Hope that helps.

You don't need pointers to character pointers at all:

int str_cmp(const char* s1, const char* s2)
{
    while (*s1 != 0 && *s2 != 0 && *s1 == *s2)
    {
        ++s1;
        ++s2;
    }
    
    if (*s1 == *s2)
    {
        return 0;
    }
    
    return *s1 < *s2 ? -1 : 1;
}

Also, there is a bug in your second implementation: it returns 1 on compareStrings("hello", "helloo"), when the correct result is -1.

Hope that helps.

You don't need pointers to character pointers at all:

int str_cmp(const char* s1, const char* s2)
{
    while (*s1 != '\0' && *s1 == *s2)
    {
        ++s1;
        ++s2;
    }
    
    if (*s1 == *s2)
    {
        return 0;
    }
    
    return *s1 < *s2 ? -1 : 1;
}

Also, there is a bug in your second implementation: it returns 1 on compareStrings("hello", "helloo"), when the correct result is -1.

Hope that helps.

Source Link
coderodde
  • 32.3k
  • 15
  • 79
  • 205

You don't need pointers to character pointers at all:

int str_cmp(const char* s1, const char* s2)
{
    while (*s1 != 0 && *s2 != 0 && *s1 == *s2)
    {
        ++s1;
        ++s2;
    }
    
    if (*s1 == *s2)
    {
        return 0;
    }
    
    return *s1 < *s2 ? -1 : 1;
}

Also, there is a bug in your second implementation: it returns 1 on compareStrings("hello", "helloo"), when the correct result is -1.

Hope that helps.