2

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?

umop apisdn
  • 653
  • 9
  • 20

1 Answers1

4

Because the two addresses are the same. Your compiler included one copy of the string "Hello" in your program and made str1 and str2 both point to it.

The C standard specifies that string literals might or might not be distinct arrays in memory, and that undefined things might happen if you modify them in order to allow the compiler to do exactly this.

hobbs
  • 223,387
  • 19
  • 210
  • 288