[C] strcmp vs. dereference and ==
Author |
Message |
Cervantes

|
Posted: 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.  |
|
|
|
|
 |
Sponsor Sponsor

|
|
 |
Mazer

|
Posted: 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

|
Posted: 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.  |
|
|
|
|
 |
Mazer

|
Posted: 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.  |
|
|
|
|
 |
|
|