Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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);
like image 498
Bhupesh Pant Avatar asked Nov 20 '25 18:11

Bhupesh Pant


1 Answers

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.

like image 182
coredump Avatar answered Nov 24 '25 22:11

coredump



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!