As if we needed another string reversal question.
All though this is probably school work I'll try to fix it...
I have a problem with the following code, that I believe should work.
int StringReverse(char* psz)
Why do you return int here?
Why don't you use std::string?
char *q = psz + strlen(psz) - 1;
while (p < q)
{
char tmp = *p;
Why don't you instead use std::swap here?
*p = *q;
*q = tmp;
p++;
q--;
Why don't you use pre incremental operators here?
Once again, why do you return the integer here?
Return values are either to state some kind of "state" (C-style) or to
return some kind of result (C++-style).
The signature of your function should rather have been:
std::string StringReverse( const std::string & input )
Or at least "void StringReverse( char * psz )"
}
Thing is, when it gets to the *p = *q line, I get an access violation.
No idea why you get this, but I have some theories...
Se further down...
Any ideas why, or what I can do to fix this?
This is how I would have done it:
std::string StringReverse( const std::string & input )
{
std::string retVal;
for( std::string::const_iterator idx = input.end();
idx != input.begin();
--idx )
{
retVal.push_back( *idx );
}
return retVal;
}
....or maybe even better...:
template<class T>
std::basic_string<T> StringReverse2( const std::basic_string<T>
& input )
{
typedef std::basic_string<T> myString;
myString retVal;
for( myString::const_iterator idx = input.end()-1;
idx != input.begin();
--idx )
{
retVal.push_back( *idx );
}
retVal.push_back( *input.begin() );
return retVal;
}
....or the _completely_ generic way...:
template<class T>
T StringReverse2( typename T::const_iterator begin,
typename T::const_iterator end )
{
--end;
T retVal;
while( end != begin )
{
retVal.push_back( *end );
--end;
}
retVal.push_back( *end );
return retVal;
}
The last one works for both std::string, std::vector and std::list...!
But you need to explicitly define in the calling of it which class you
wish to use, e.g.:
"std::string x = StringReverse<std::string>( or.begin(), or.end() );"
If you are persistant on using c-strings (maybe you're a game
programmer) you can allways do it like this, but I would have choosen
ANY of the above solutions before I did it like this:
void StringReverse( char * input )
{
char * begin = input;
char * end = input+(strlen(input)-1);
while( begin < end )
{
char tmp = *end;
*end = *begin;
*begin = tmp;
++begin, --end;
}
}
Why your solution doesn't work I wouldn't know, but I tried it in
Visual Studio and I added up a "char * tmp = "Thomas Hansen";" line
and when I tried to reverse that line I got an "access violation".
This is probably since Visual Studio define that memory as "read only"
since it's statically linked into the process image...
Don't know if this is a bug or not....?
Why can't we do:
char * tmp = "Thomas Hansen";
StringReverse( tmp );
Anybody?!?
Suggestions?!?
Is it illegal?!?