Bhupesh Pant
Bhupesh Pant

Reputation: 4349

How strcmp() is returning -1 even though the two values are same?

When I am giving an input as 'x' the compVal is giving the value as -1. I am expecting 0 since both the values are same. Please someone explain the reason.

char ch = getchar();
int compVal = strcmp("x", &ch);

Upvotes: 2

Views: 2972

Answers (6)

coredump
coredump

Reputation: 3107

You have to give to strcmp two strings. A string is an array of char with the last value being \0.

In your example, the second value you are passing it is just the address of a char and there is no string terminator so the function goes blindly ahead until it finds a 0 ( same thing as \0).

You should either use strcmp with a char vector like char ch[2] ( One value for the character you want and the other for the \0 I mentioned earlier or, in your case you should just use the == operator since you want to compare only one character.

Upvotes: 8

eyalm
eyalm

Reputation: 3366

You can compare characters directly:

char ch = getchar();

if ('x'==ch)
{
    /* ... */
}

Upvotes: 0

Aloys
Aloys

Reputation: 682

You compare the constant string "x" with a char 'x'. By giving the pointer to that char your make strcmp think it is comparing strings. However, the constant string "x" ends with '\0' but the char you use as a string does not end with '\0', which is a requirement of a string.

x\0
x ^ <- difference found

However, what you are doing might result in a segmentation fault on other systems. The correct fix for this is to put a terminating null character after the input or just compare the chars (in this case that is even better!).

Upvotes: 2

Hogan
Hogan

Reputation: 70529

These are two different data types.

Remember that internally "x" is stored as 'x' and '\0' in memory. You need to make memory look the same for it to work as a string in C.

This will work:

char ch[2];
ch[0] = getchar();
ch[1] = 0;
int compVal = strcmp("x",ch);

Here you compare two arrays of characters. Not an address of a single char and a char*.

Upvotes: 2

Luefox
Luefox

Reputation: 63

You probably shouldn't be using strcmp() to compare single characters.

Char variables can just be compared using relational operators such as ==, >, >= etc

I would think the reason that you're comparison isn't working is that you're comparing a string to a single character. Strings have a null terminator "\0" on the end of them, and it will be added if it isn't there. Therefore string compare is correctly telling you that "x\0" is not equal to "x".

Upvotes: 4

Alok Save
Alok Save

Reputation: 206566

strcmp reads from the input address untill a \0 is found. So you need to provide NULL terminated strings to strcmp. Not doing so results in Undefined behavior.

Upvotes: 3

Related Questions