I'm posting a snippet of my project that I'm currently having trouble with.
In the function reverse_ I'm passing "dog", just to simply see if "dog" would reverse to "god". However I keep getting an exception thrown error at *s=*end. I'm not quite sure what this exception thrown error is telling me exactly other than it has to do something with memory or how to fix it.
size_t strlen(constchar* p)
{
int len;
len = 0;
while (*p != '\0')
{
p++;
len++;
}
return len;
}
char* reverse_(char *s){
char* end = s + strlen(s) - 1; //so that char* end starts on "g"
//rather than the null terminator
while (s < end) {
char c;
c = *s;
*s = *end; //here i get the following: Exception thrown: write
// access violation. s was 0x2B8B30.
*end = c;
s++;
--end;
}
return s;
}
ah you're right, I declared "dog" as a read-only, explains why it wasn't working earlier. Now reverse_ almost works, excepts it only outputs "od" instead of "god"
To be completely honest, I'm not sure what the character s is pointing to when returning at line 29.
To be completely honest, I'm not sure what the character s is pointing to when returning at line 29.
Well, providing the rest of the reverse function is working (it seems to be), s is pointing to somewhere half-way through the sting. If it has an odd number of letters ("dog" has 3) then it points to the middle letter 'o'. If it is even ("abcd" has 4) then it points to the letter just past the middle.
But to fix the problem, the simplest approach is to save the original value of s. i.e. use a separate variable to store the value of s at the start of the function. Then at the end, return that original value.
(Or something like that. There's more than one way to write the code).
"Reverse a string in place" - yes, I would think that your code meets that requirement. That is, it doesn't make a copy, it actually modifies the original string - which is why it gave a problem when the string was read-only. So yes, it's ok.
One suggestion. Instead of calling a separate strlen() function, you might integrate that into the reverse function.
All you need do is set end to the same as s. Then loop until the null is found. Then subtract 1, so end points to the last actual character.