0

I'm currently working my way through CS50x and just tinkering around with some of the practice problems from Week 1 and testing the limits of my knowledge. Could someone help me understand why the two strings "my_month" and "your_month" aren't equal?

I've tested it and if I print the string for "my_month" it prints "October" - but if I enter "October" for "your_month" it doesn't seem to think that it is equivalent to the string in the array.

string month [] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
string my_month = month [9];
string your_month = get_string("What month were you born? ");

if (your_month == my_month)
{
    printf("%s\n", your_month);
}
mr_jay
  • 3
  • 1
  • If you looked up, how `string` is defined in your case, you will probably find `char*`. So, it is a pointer and if you compare 2 strings, the addresses differ. You want to use the C library function `strcmp()` instead. (Yes, back then all those language designers and library authors had keyboards with defective vowel keys....) – BitTickler Jun 28 '22 at 05:11

2 Answers2

2

In the CS50 library, the data type string is just a typedef for a char *, i.e. a pointer or reference to a string. A variable of type string therefore does not actually contain a string. It only contains the memory address of a string.

In the line

if (your_month == my_month)

you are not comparing the actual string content. You are comparing the pointers, i.e. the addresses of the strings. Since the pointers are referring to two different strings (that have the exact same content), the addresses are not equal, so the if condition is false.

If you want to compare the actual content of the strings, instead of memory addresses of the strings, then you must use the function strcmp instead:

if ( strcmp( your_month, my_month ) == 0 )
Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
1

The reason is because technically they aren't equal. When you use '==' on strings, what you are comparing is their addresses.

To compare the contents of 2 string you have you have to use strcmp().

So your code should look like this:

if (strcmp(your_month, my_month) == 0)
{
    printf("%s\n", your_month);
}

strcmp() works by comparing each character's ASCII value. So it can also tell you if the first string is "more" or "less" than the second one.

For example:

strcmp("lol", "LOL");

Will return a value bigger than 0 which means the ASCII values of "lol" are higher than those of "LOL"