CompuServe Thread

#C pointers

4 messages in this thread
#30393From: Steven ParkNov 26, 1992 9:55 PM
How do you make a char pointer comparison? If you go …. char *name = "Bob"; if(name == "Bob") printf("Hello %s. \n",name); you'll never see `Bob' printed.
#30397From: Steve AhlstromNov 27, 1992 12:35 AM
if (!(strcmp(name, "Bob"))); -sja
#30402From: SyndesisNov 27, 1992 1:31 PM
The way C see it, you've got one pointer called 'name' that gets initialized at compile time to point at a bit of data that happens to be a string of "Bob", while your comparison compares the value of 'name' (which was set to point at the first "Bob" string) to another DIFFERENT bit of data that happens to be another string of "Bob". With the 'strcmp()' function, you get a comparison of two strings.
#30404From: Greg Comeau@Comeau CmptgNov 27, 1992 4:42 PM
>How do you make a char pointer comparison? If you go …. char *name = "Bob"; >if(name == "Bob") printf("Hello %s. \n",name); >you'll never see `Bob' printed. And just to add to the comments already offered. Note that the string literal in the if statement is an unnamed region of storage. Its utterance in your if statment results in the *address* of where the B is. This makes sense if you look at how the "Bob" in 'char *name = "Bob";' works. name now points at the B in that Bob. So, name == "Bob" is comparing addresses and not string, and it is the latter which I think that you want to do. To make this more complicated, your C implementation actually has the liberty to put the two literals into the same storage and so the possibility did exist that it would have printed the Hello… string. But that is not the way you intended the result and hence you should stay away from that approach and use the strcmp as was suggested.