array & pointer problem

Discussion in 'C' started by answerme, Dec 10, 2010.

  1. answerme

    answerme New Member

    Joined:
    Dec 17, 2007
    Messages:
    114
    Likes Received:
    0
    Trophy Points:
    0
    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
     
  2. virxen

    virxen Active Member

    Joined:
    Nov 24, 2009
    Messages:
    387
    Likes Received:
    90
    Trophy Points:
    28
    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;
    }
    
     
  3. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    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.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice