Search code examples
c++arraysstringstrcmp

Why does my version of strcmp not work?


I have a 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 is

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


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

However, I get the output of 1, meaning they are not equal to each other. If I swap a and b's position in the function call I get -1. I am not sure why I am unable to get the 0 return in my comparison when my char's are both 'f'. I feel like this is so basic and I don't know why my comparison is off

str1[i] > str2[i] 

Solution

  • You've left your arrays uninitialized and only changed the first elements of each. This means that instead of comparing the strings "f" and "f" against one another, you're comparing two blocks of 20 bytes each against one another, except that each of the blocks starts with an "f". (Actually, since those arrays aren't null-terminated, you're comparing two random regions of memory together!)

    Try changing your test cases so that you use strcpy to initialize the arrays. That should fix your issue.