I am writing reverseString function by myself. (For test use) And I use iOS platform to run my c code, which sounds weird, but again, for test use…
Here is my code:
-(char *) reverseString:(char *)str
{
char *end = str;
char tmp;
if (str)
{
while (*end) { end++; }
--end;
NSLog(@"%c", *end);
while (end>str)
{
tmp = *str;
*str = *end;
str++;
*end = tmp;
end--;
}
}
NSLog(@"%s", str);
return str;
}
After running the function by calling:
char *testChar = "abcd";
[self reverseString:testChar];
I received the error on line:
*str = *end;
Thread 1: EXC_BAD_ACCESS(code=2, address=0x2de4)
I don’t really know understand what’s wrong with the pointer here…Anyone has any idea?
You can’t modify a string literal. Use a char array instead.