+ 2

If i directly compare two strings on printf it produce only null value..why.?

22nd Aug 2018, 4:32 AM
M.MANIVANNAN
M.MANIVANNAN - avatar
5 Respuestas
+ 1
#include<stdio.h> void main() { char a[]="mani"; char b[]="mani"; printf("%s",a==b); } if i compiled this .this produce the output like [null]
22nd Aug 2018, 5:51 AM
M.MANIVANNAN
M.MANIVANNAN - avatar
+ 3
I guess it's better to use designated function for string comparison rather than == operator, and Ketan Lalcheta was right, when he said a==b is not evaluated as string, but a boolean instead. #include <stdio.h> #include <string.h> int main() { char a[]="mani"; char b[]="mani"; if(strcmp(a, b)) printf("%s differs with %s", a, b); else printf("%s equals to %s", a, b); return 0; }
22nd Aug 2018, 6:37 AM
Ipang
+ 2
M.MANIVANNAN a==b is no longer a char[].. it is Boolean operation... to print your value, put %s , a and put %s,b in two different printf
22nd Aug 2018, 6:05 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 2
if I'm not mistaken, a==b and strcmp(a,b) are completely different things. In the first case, you are comparing pointers to memory positions and the value will be false if both positions are not the same, even if the contents are. For example, a points to a position 1000 that contains 'cat', b points to position 2000 that also contains 'cat'. a==b will be false and strcmp(a,b) will be true. So Ipang's advice is solid. a==b would be true only if you first did a=b;. i.e., made a point to the same memory position of b.
23rd Aug 2018, 3:36 PM
Eduardo Costa e Silva
+ 1
Please attach your code link, it's difficult to imagine what you really mean.
22nd Aug 2018, 5:47 AM
Ipang