0

Why is

if (strcmp(candidates[i], name) == 0)

working, but:

if (name == candidates[i])

not working? I have also tried with casting string on both sides, but doesn't work. I have checked via printf, candidates[0] and name have identical strings, but somehow the bool doesnt turn true.

I would like to comprehend why this is the case.

Thank you for your time

1
  • If I understood correctly, name == candidates[i] would check whether they are the exact same thing, i.e. share / point to the same memory? As in, did I ever assign candidates[i] = name Have I understood this correctly? Commented Sep 17, 2021 at 14:45

1 Answer 1

2

Review the week 3 lecture starting at the 40 minute mark. From the transcript

And it turns out, for reasons we'll explore in more detail next week, it is not sufficient to do what we did before and do something like this if I'm searching for "Ron." It turns out that in C, you can't use equals equals to compare two strings. You can for an int, you can for a char. And we've done both of those in the past. But there's a subtlety that we'll dive into in more detail next week that means you can't actually do this.

And this is curious, because if you have prior programming experience in languages like Python or the like, you can do this. So in C you can't, but we'll see next time why. But for now, it turns out that C can solve this problem, and historically the way you do this is with a function.

So inside of the string.h header file, there is not only a declaration for strlen, the length of a string like last week. There's another function called strcmp. And "stir compare," for short, S-T-R-C-M-P, allows me to pass in two strings, one string that I want to compare against another string.

Spoiler: The technical reason is that strings are actually pointers, which is to say addresses. string == string will compare the addresses, not the data at those addresses.

You must log in to answer this question.

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