
-----------------------------------
Cervantes
Thu Jun 29, 2006 8:37 am

[C] strcmp vs. dereference and ==
-----------------------------------
Is there any advantage to using strcmp over dereferencing the pointers and comparing with ==?


#include 
#include 

int main()
{
    char *foo = "major major";
    char *bar = malloc(sizeof(char) * 12);
    strcpy(bar, foo);
    if (*foo == *bar) printf("Hello\n");

    return 0;
}


vs.

#include 
#include 
#include 

int main()
{
    char *foo = "major major";
    char *bar = malloc(sizeof(char) * 12);
    strcpy(bar, foo);
    if (strcmp(foo, bar) == 0) printf("Hello\n");

    return 0;
}


Both output the "Hello\n".

Both output the "Hello\n" even if I allocate more than 12 bytes to bar.

Thanks. :)

-----------------------------------
Mazer
Thu Jun 29, 2006 9:02 am


-----------------------------------
If you dereference the character arrays, you will be left with two characters (the first character from each array).
char *foo = "Hello";
char *bar = "Hippo";
So 'H' == 'H', even though "Hello" != "Hippo".

-----------------------------------
Cervantes
Thu Jun 29, 2006 12:03 pm


-----------------------------------
Of course! 

I just realized that as I walked in a few minutes ago. I think I said this yesterday, but "hurray for sudden flashes of realization!"

Thanks, Mazer. :)

-----------------------------------
Mazer
Thu Jun 29, 2006 12:06 pm


-----------------------------------
Happy to be of service.

Actually, I was honestly just happy to use "Hippo" in a post.  :wink:
