In the lecture of week 4 in CS50x, David illustrates how two strings can't be compared with two equal signs (==), and instead, strcmp() has to be used.
I can't reproduce this locally or on CS50's IDE online. I can compare two strings with ==, as long as I don't create these two strings in runtime using get_string().
The code I'm running:
int main(void)
{
char *str_1 = "This is a string!";
char *str_2 = "This is a string!";
printf("str_1: %s, str_2: %s\n", str_1, str_2);
printf("str_1 address: %p, str_2 address: %p\n", &str_1, &str_2);
printf("str_1 == str_2: %d\n", str_1 == str_2);
}
The output:
str_1: This is a string!, str_2: This is a string!
str_1 address: 0x7ffebe62b958, str_2 address: 0x7ffebe62b950
str_1 == str_2: 1
Somehow, I am able to compare strings without strcmp(), and I have no idea why. It's also clear that the two strings are stored in different memory locations, so the pointers are not the same.
Can someone explain this behavior?
(I researched on stackoverflow, and I didn't find anyone asking the same question. In fact I found people asking the opposite: how to compare strings because using == doesn't work for them)