I am trying to create a non-recursive method to swap a c-style string. It throws an exception in the Swap method. Could not figure out the problem.
void Swap(char *a, char* b)
{
char temp;
temp = *a;
*a = *b;
*b = temp;
}
void Reverse_String(char * str, int length)
{
for(int i=0 ; i <= length/2; i++) //do till the middle
{
Swap(str+i, str+length - i);
}
}
EDIT: I know there are fancier ways to do this. But since I’m learning, would like to know the problem with the code.
No it doesn’t. Creating a temporary character and assigning characters can not possibly throw an exception. You might have an access violation, though, if your pointers don’t point to blocks of memory you own.
The
Reverse_String()function looks OK, assumingstrpoints to at leastlengthbytes of writable memory. There’s not enough context in your question to extrapolate past that. I suspect you are passing invalid parameters. You’ll need to show how you callReverse_String()for us to determine if the call is valid or not.If you are writing something like this:
Then you will definitely get an access violation, because
strpoints to read-only memory. Try the following syntax instead:This will actually make a copy of the
"Foo"string into a local buffer you can overwrite.