When we compare strings in C, we are careful to use strcmp
(or its other variants) to do equality checks. For example, if one string is char hello1[7] = "hello!"
and another string is char hello2[7] = "hello!"
, we can check if their contents are equal using strcmp
. However, we cannot use ==
since ==
will compare the address of the first element of each array (due to array decay), and that is always false.
So why is it that when I try to compare two char *
with ==
, the result is true? For example:
int main() {
char *str1 = "Hello";
char *str2 = "Hello";
if (str1 == str2) {
printf("equal\n");
} else {
printf("not equal\n");
}
}
This will print equal
. Based on my understanding, a pointer is essentially an address, so a char *
is an address of a location containing a character. So how can two addresses be the same here?