Jump to content
  • Advertisement

Archived

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

TheOne1

string question

This topic is 5318 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

#include <iostream>

using std::cout;
using std::endl;
using std::cin;

void mystery1( char *, const char * );

int main()
{
	char string1[ 50 ], string2[ 50];

	cout << "Enter two strings: ";
	cin >> string1 >> string2;
	mystery1( string1, string2 );
	cout << string1 << endl;

	return 0;
}

void mystery1( char *s1, const char *s2 )
{
	while ( *s1 != '\0' )
		++s1;

	for ( ; *s1 = *s2; s1++, s2++ )
		;
}
when i type in two strings, lets say for example quake, con what happens when ++s1 is reached? [edited by - TheOne1 on March 26, 2004 1:40:18 AM]

Share this post


Link to post
Share on other sites
Advertisement
At the end of the while loop it will be pointing past the end of the character array strait into our best friend: undefined behaviour

Share this post


Link to post
Share on other sites
Not if there''s still space in the buffer. It''s skipping ahead to the null-terminator of the ''string'' at s1, which might (hee hee) be shorter than the 50 chars that are allocated there in main. In which case it will happily continue along with the for loop, with the net effect of... yeah, compile it yourself and find out.

Share this post


Link to post
Share on other sites
If string1 is twice the size of string2 it will work, but it''s still horrible code.

You *are* trying to append string2 to string1... right?

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!