Code: #include<stdio.h> main() { char s1[]="H1"; char s2[]="H1"; if(s1==s2) printf("EQUAL"); else printf("NOT EQUAL"); } [B]OUTPUT : NOT EQUAL[/B] Code: #include<stdio.h> main() { char *s1="H1"; char *s2="H1"; if(s1==s2) printf("EQUAL"); else printf("NOT EQUAL"); } [B] OUTPUT : EQUA[/B]L Whats the difference b/t these 2 programs
wrong syntax s1==s2 does not compare two string , you must use strcmp function instead Code: #include<stdio.h> #include <string.h> int main(){ char s1[]="H1"; char s2[]="H1"; if(strcmp(s1,s2)==0) printf("EQUAL"); else printf("NOT EQUAL"); getchar(); return 0; }
The second only prints EQUAL because the compiler has merged those duplicate strings and set the POINTERS in s1 and s2 to the same address. s1==s2 compares the POINTERS, not the strings those pointers are pointing to. As virxen says, to compare the strings you have to use strcmp.