array & pointer problem

answerme's Avatar, Join Date: Dec 2007
Ambitious contributor
Code:
#include<stdio.h>
main()
{
char s1[]="H1";
char s2[]="H1";
if(s1==s2)
printf("EQUAL");
else
printf("NOT EQUAL");
}
OUTPUT : NOT EQUAL
Code:
#include<stdio.h>
main()
{
char *s1="H1";
char *s2="H1";
if(s1==s2)
printf("EQUAL");
else
printf("NOT EQUAL");
}


OUTPUT :  EQUAL
Whats the difference b/t these 2 programs
0
virxen's Avatar, Join Date: Nov 2009
Pro contributor
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;
}
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
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.