Why is my strcmp version not working?

I have my own version of strcmp that looks like this:

int strcmp(char str1[], char str2[])
{
    int i = 0;
    while ((str1[i] == str2[i]) && (str1[i] != '\0'))
    {
        i++;
    }

    if (str1[i] > str2[i])
        return 1;

    if (str1[i] < str2[i])
        return -1;

    return 0;
}

And my test case

char a[20];
char b[20];
b[0] = 'f';
a[0] = 'f';


cout << strcmp(b, a) << endl;

However, I get output 1, that is, they are not equal to each other. If I swap a and b in a function call, I get -1. I am not sure why I cannot get 0 returns in my comparison when my char both are "f". I feel this is so thorough, and I don't know why my comparison is disabled.

str1[i] > str2[i] 
+4
source share
2 answers

. , "f" "f" 20 , , "f" . ( , , !)

, strcpy . .

+8

, NUL, , f, .

, , :

a[1]=b[1]=0;

:

char a[20]="f";
char b[20]="f";

strcpy

strcmp("f", "f") 

( const ).

+3

Source: https://habr.com/ru/post/1627730/


All Articles