Jump to content
  • Advertisement

Archived

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

skitzo_smurf

darn strings

This topic is 6613 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
Advertisement
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

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!