/* Reverse a string in place
*/
#import <stdio.h>
void reverse(char * str);
int main()
{
char * string = "This is a string.";
printf("%s\n", string);
reverse(string);
printf("%s\n", string);
}
void reverse(char * str)
{
char * start = str;
char * end = str;
if(0==*str)
return;
//Find the end
for(;0 != *(++end););
end--;
do
{
*end = *end ^ *start;
*start = *end ^ *start;
*end = *end ^ *start;
}while(++start < --end);
}
我不确定为什么这个段会出错。是因为我用常量字符串初始化我的char *?
答案 0 :(得分:6)
您正在尝试修改字符串常量。替换:
char * string = "This is a string.";
与
char string[] = "This is a string.";
解决这个问题。