0

This question concerns variables, pointers and addresses as addressed in Lecture 4. I understand that strings are not "real" in the way that integers and characters are, and are just defined as "something between a character whose address is known and the first null." My confusion is about when trying to compare strings as against comparing int/char. The following code will always produce "Different" because the program is actually checking the base addresses of s and t, which are different:

int main(void)
{
    // Get two strings
    string s = get_string("s: ");
    string t = get_string("t: ");

    // Compare strings' addresses
    if (s == t)
    {
        printf("Same\n");
    }
    else
    {
        printf("Different\n");
    }
}

But, in that case, why is the computer checking the values, and not the base addresses for, say, integers:

int main(void)
{
    // Get two integers
    int i = get_int("i: ");
    int j = get_int("j: ");

    // Compare integers
    if (i == j)
    {
        printf("Same\n");
    }
    else
    {
        printf("Different\n");
    }
}

Is it because "strings" are actually pointers, and the first code chunk is actually comparing pointers, though the values they are pointing to are identical?

1

You have it right. In your code if(s == t) is actually comparing the address stored in s and t, not what is stored at those addresses. Further, you'd have to compare each char in one string to the char in the other.

OTOH, int vars are not pointers. All the operators are geared to go straight to the stored values in regular vars like ints and floats. And, you can compare the contents of memory at an address stored in a pointer. Good exercise to learn how to use &.

If you want to compare strings, use strcmp() or strcasecmp().

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • 1
    Thanks, Cliff. This was super useful in clarifying. Upvoted and marked as accepted. Cheers!
    – user3671
    May 14 '20 at 5:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .