strcmp function


I was actually trying to compare a single letter of 2 character arrays using the strcmp function. If the letter was the same, it would print “Awesome!” In this case, it should print “Awesome” along with the lengths because the first letter of “Sneha” and “Sasha” is the same. But instead, it’s giving me heaps of errors. I tried googling it up but was unable to understand. The code along with the errors is in image format.

Sorry if it’s too simple :frowning:

this link is not working for me…

u need to pass 2 strings in that fxns…i.e. char*…not char as u r doing!!!

to compare 2 chars u can directly use “==” operator…hope this helps!!!

@kunal361 I tried converting char to char but it gives an error: cannot convert char* to char*

Tried your second suggestion (with char not char*) by directly using == and it worked! :slight_smile:

And not only that, (with char not char*) when I modified the program slightly by removing the indices and making strcmp compare 2 strings instead of 2 characters, I noticed that strcmp seems to work when comparing 2 strings, but not 2 characters. Is it true?

strcmp fxn is used for comparing 2 strings…not 2 chars!!!

u can see how to use that fxn here…LINK!!!

But strcmp function works without converting char to char* then why is char* like you said necessary? Sorry for bothering you with so many questions.

char* or char[] is similar to string…the fxn strcmp is defined in such a way…i.e. to accept 2 char*s or char[]s…i.e. strings!!!

Call to strcmpp is incorrect.
It should be

strcmp(&s1[0], &s2[0])

or simply

strcmp(s1, s2);

And strcmp compares two string and not characters, to compare characters, use the following

if(s1[0] == s2[0])

If you want to find any one of the character match and not the one at zero index, use find_first_of

1 Like