Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   array & pointer problem (http://www.go4expert.com/forums/array-pointer-problem-t24137/)

answerme 10Dec2010 11:12

array & pointer problem
 
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 :  EQUA
L

Whats the difference b/t these 2 programs

virxen 10Dec2010 19:20

Re: array & pointer problem
 
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;
}


xpi0t0s 12Dec2010 21:07

Re: array & pointer problem
 
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.


All times are GMT +5.5. The time now is 15:17.