Archived

This topic is now archived and is closed to further replies.

darn strings

This topic is 6363 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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=-..

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites