What's wrong here? blah=="abcdef"
doesn't return a true value
int main(void)
{
char blah[] = "abcdef";
if(blah=="abcdef")
printf("%s\n", blah);
}
What's wrong here? blah=="abcdef"
doesn't return a true value
int main(void)
{
char blah[] = "abcdef";
if(blah=="abcdef")
printf("%s\n", blah);
}
For comparing strings you should use something like strcmp()
instead.
==
and !=
compares base addresses hence they dont actually compare the value of the string.
Always take care when comparing "objects" vs "value of objects"
When you're comparing two strings with ==
, you're actually checking equality of the pointers (base address) of the two strings which is obviously always false.
The correct way to compare the two strings would be to either use the inbuilt strcmp()
function from <string.h>
or to define a string equality checker function by yourself as follows :
int isEqual(char *a,char *b)
{
int i=0;
while(1)
{
if(a[i]==b[i])
{
if(a[i]=='\0')
return 1;
i++;
continue;
}
else
return 0;
}
}
You are comparing a string
literal to a character array
. Try below.
Use strcmp()
to compare the contents of strings.
OR
char buffer[5];
char word[5] = "WORD";
test(buffer, word, 5);
short test(char buffer[], int length) {
int i;
char word[5] = "WORD";
for(i = 0; i < length; i++) {
if(buffer[i] != word[i]) {
return 0;
}
}
return 1;
}
You should use strcmp()
function to compare string.
blah=="abcdef"
return always false because you compare 2 memory address.
int main(void)
{
char blah[] = "abcdef";
if(strcmp(blah,"abcdef") == 0 ) //return 0 if equal, !=0 if not equal
printf("%s\n", blah);
}