Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 [C] strcmp vs. dereference and ==
Index -> Programming, C++ -> C++ Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Cervantes




PostPosted: Thu Jun 29, 2006 8:37 am   Post subject: [C] strcmp vs. dereference and ==

Is there any advantage to using strcmp over dereferencing the pointers and comparing with ==?

code:

#include <stdlib.h>
#include <stdio.h>

int main()
{
    char *foo = "major major";
    char *bar = malloc(sizeof(char) * 12);
    strcpy(bar, foo);
    if (*foo == *bar) printf("Hello\n");

    return 0;
}


vs.
code:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

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. Smile
Sponsor
Sponsor
Sponsor
sponsor
Mazer




PostPosted: Thu Jun 29, 2006 9:02 am   Post subject: (No subject)

If you dereference the character arrays, you will be left with two characters (the first character from each array).
code:
char *foo = "Hello";
char *bar = "Hippo";

So 'H' == 'H', even though "Hello" != "Hippo".
Cervantes




PostPosted: Thu Jun 29, 2006 12:03 pm   Post subject: (No subject)

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. Smile
Mazer




PostPosted: Thu Jun 29, 2006 12:06 pm   Post subject: (No subject)

Happy to be of service.

Actually, I was honestly just happy to use "Hippo" in a post. Wink
Display posts from previous:   
   Index -> Programming, C++ -> C++ Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 4 Posts ]
Jump to:   


Style:  
Search: