-2

This piece of code works fine. But I'm wondering if it can be done in a more efficient way?

More specifically this part *(s1 + i) if it possible to force it to sequence through entire array character by character via pointer for example *s1++. My task to do this function compareStrings without index array [].

 int  compareStrings(const char  *s1, const char  *s2)
{
    int i = 0, answer;
    //  i - to sequence through array of characters
    // pointer to character string1 and character string2
    while (*(s1 + i) == *s2 + i && *(s1 + i) != '\0'&& *(s2 + i) != '\0')
    {
        i++;
    }

    if ( *(s1 + i) < *(s2 + i) )
        answer = -1;               /* s1 < s2  */
    else if ( *(s1 + i) == *(s2 + i) )
            answer = 0;                 /* s1 == s2 */
        else
            answer = 1;                 /* s1 > s2  */

        return answer;

But I want to change it to s1++ and s2++ insted of *(s1 + i) and *(s2 + i). I've tried to implement this idea with pining an extra pointer to the beginning but I've failed. Here the code -->

int  compareStrings(const char  *s1, const char  *s2)
{
    int answer;
    char **i = s1, **j = s2;
    // i and j - to sequence through array of characters
    while (*(i++) == *(j++) && *(i++) != '\0'&& *(j++) != '\0');

    if (*i < *j)
        answer = -1;               /* s1 < s2  */
    else if (*i == *j)
        answer = 0;                 /* s1 == s2 */
    else
        answer = 1;                 /* s1 > s2  */

    return answer;
} 
Yellowfun
  • 418
  • 1
  • 9
  • 21

2 Answers2

2

In order to compare C-strings, all you need is

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;
}
coderodde
  • 1,269
  • 4
  • 17
  • 34
1

The latter code isn't working, because you increment s1 twice:

*s1++ == *s1++

This will:

  1. Get the value of s1
  2. Dereferene it
  3. Increment by 1
  4. Then on the right side, do the same again
  5. And only then compare it.

You essentially are doing this:

*(s1) == *(s1+1)

I think that should actually be:

*s1++ == *s2++
Dan
  • 630
  • 5
  • 8
  • 2
    Are you sure about `*(s1+1) == *(s1+2)` ? It would be `*(s1) == *(s1+1)` because postfix increment returns old value. – Yuriy Ivaskevych Feb 03 '17 at 10:21
  • Good catch. Corrected that! – Dan Feb 03 '17 at 11:19
  • I'm not sure, but for me, `*s1++ == *s1++` has **_undefined behavior_**, because `==` isn't a [sequence point](http://stackoverflow.com/questions/3575350/sequence-points-in-c), so, you don't know which `s1++` (left or right) are evaluated first. so you can absolutely not say that is equivalent to ` *(s1) == *(s1+1)`, because it can also be `*(s1+1) == *(s1)` or something else (undefined behavior) – Garf365 Feb 03 '17 at 11:22