1

I am new to the C language. Please, could someone tell me why I am always getting zero as output when comparing differing strings using my own implementation of strcmp?

I wrote the function xstrcmp to compare two strings: if they are equal, then it returns 0; otherwise, it returns the numeric difference between the ASCII values of the first non-matching pair of characters.

    #include<stdio.h>

    int xstrcmp(char*,char*);

    int main()
    {   
        int i;
        char string1[]="jerry";
        char string2[]="ferry";
        i=xstrcmp(string1,string2);
        printf("difference=%d\n",i);
        return 0;
    }

    int xstrcmp(char*p,char*q)
    {
        int m;
        while(*p!=*q)
        {
             if((*p=='\0')&&(*q=='\0'))
                break;
          p++;
          q++;
        }
        m=(*p)-(*q);
        return m;
    }
3
  • 5
    Hint: Take a closer look at this line: while(*p!=*q) Commented Jul 9, 2012 at 8:47
  • while(*p==*q) will come here..thnx for the hint mate Commented Jul 9, 2012 at 9:02
  • You have asked several questions but haven't accepted any answers, mate. Commented Jul 9, 2012 at 21:19

2 Answers 2

3

You loop until you find equal chars, then you subtract them -- so of course the result is always 0.

Also, the condition inside the loop will always fail ... if the chars aren't equal, they can't both be NUL.

That should be enough for you to fix your code.

Sign up to request clarification or add additional context in comments.

Comments

0

The reason why you get zero always is that your while loop while(*p!=*q) means that the loop will execute as long as the characters are NOT same.

The exit from loop will happen when *p and *q have the same value.

Hence the return value, which is m=(*p)-(*q); will always be zero.

while (*p == *q) /* as long as they have same value, loop; otherwise exit */
{
      p++; /* increment the pointers */
      q++;
}
return (*p)-(*q);

would be the way to go.

1 Comment

This has undefined behavior for equal strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.