Advertisement

darn strings

Started by July 13, 2000 08:47 AM
1 comment, last by skitzo_smurf 24 years, 5 months ago
could someone tell me why the following source code outputs NOT EQUAL instead of hi ?
    

void fn(char* c)
{
  if(c == "hi")
     cout << "EQUAL";
   else 
     cout << c;
}


int main()
{
   char str[1][3];
   strcpy(str[0],"hi");

   fn(str[0]);

   return(0);
}

    
thanks, skitzo_smurf
"Innocent is just a nice way to say ignorant, and stupidity is ignorance with its clothes off."words of,skitzo_smurf
That''s because "c" is a pointer to the first char in your string, and not the STRING itself. In order to check if two strings are the same, you can use the strcmp() funcy... it''s used as follows...

    void fn(char* c){  if(strcmp(c, "hi") == 0)     cout << "EQUAL";   else      cout << c;}int main(){   char str[3] = "hi";   fn(str);   return(0);}    


Hope this helps!


..-=ViKtOr=-..
Advertisement
By having

(c == "hi")

you are comparing the address of c to "hi" not the content of c. The comparison will never be equal. Instead try

(strcmp(c,"hi") == 0)

That will work.

This topic is closed to new replies.

Advertisement