user3328187
user3328187

Reputation: 303

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] 

Upvotes: 4

Views: 220

Answers (2)

Matteo Italia
Matteo Italia

Reputation: 126827

Your test case is broken, you are missing the NUL terminator, so you are comparing two strings that start with an f and go on with whatever garbage is on the stack.

You can fix it by explicitly adding the terminator, like:

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

or initializing them directly with the relevant string literal:

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

or by using an strcpy, or comparing directly two string literals

strcmp("f", "f") 

(once you added const to your parameters).

Upvotes: 3

templatetypedef
templatetypedef

Reputation: 372814

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.

Upvotes: 8

Related Questions