Sorry in advance for the ignorance. I don't fully understand how to compare char arrays in C. I was originally comparing two char arrays in c with the simple ==
operator.
So in a C function, I would do something like this.
char *a = "test";
char *b = "test";
if (a == b) ..do something
But I read that I should be using strcmp
instead of ==
like this.
char *a = "test";
char *b = "test";
if (0 == strcmp(a, b)) ..do something
Which one is correct and why? What is the other one doing?
if (a == b)
Here you are comparing pointers and not the strings
strcmp(a, b)
Here you are comparing strings
Which one is correct and why? What is the other one doing?
Since there are 2 strings stored in different memory locations or if the same string is being stored there is possibility a==b
comparing pointers doesn't make sense.What you want is to compare the contents of the locations the pointers are pointing to. Which is done by strcmp()
and this is the right way to compare the strings.
For example :
#include <stdio.h>
int main(void) {
char *a = "test";
char *b = "test";
printf("%p\n %p",(void *)a,(void *)b);
return 0;
}
The output is
0x8048540
0x8048540
So both the pointers a and b are pointing to the same memory location a==b
Note that here what we compare is not the actual characters in the string but just the pointers.
I ran the same code on another machine and the locations in which this string was stored was different.
0x4005f8
0x4005fd
So now even though the strings might be same you see a != b
.
Hence use strcmp()
to compare strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With