I have a question about comparing a single char of a string in C inside a function. The code looks like this:
int fq(char *s1){
int i;
for(i=0;i<strlen(s1);i++){
if(s1[i]=="?"){
printf("yes");
}
}
return 1;
}
Even if s1="???" it never prints out yes. I have managed to solve the problem but i am curious as to why it works one way but not the other. This is the piece of code that works:
int fq(char *s1,char *s2){
int i;
char q[]="?";
for(i=0;i<strlen(s1);i++){
if(s1[i]==q[0]){
printf("yes");
}
}
return 1;
}
Because the first sample compares addresses instead of characters.
There is no string type in c and the == operator when applied to an array or a pointer, compares the addresses instead of the contents.
Your function would be correctly written like this
int fq(char *s1,char *s2)
{
int i;
for (i = 0 ; s1[i] ; ++i)
{
if (s1[i] == 'q')
printf("yes");
}
return 1;
}
you can compare s1[i] to 'q'.
"?" Isn't a char but a string with just one char
'?' Is a char and should return true in s1[i] == '?'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With