问一个构造回文函数的问题。
#include<iostream>
using namespace std;
char* palindrome(char* s)
{
int len = strlen(s);
char* p1 = s;
char* p2 = &s[len];
char* temp;
while(p1<p2)
{
temp=p1;
p1=p2;
p2=temp;
p1++;
p2--;
}
return s;
}
void main()
{
char str[20];
cin.getline(str,20);
cout<<palindrome(str);
}
请问问题在哪?? 为什么运行后输出结果不变,例如:sun sun。 并没有反序啊?
[解决办法]
char* palindrome(char* s)
{
int len = strlen(s);
char* p1 = s;
char* p2 = s+len-1; // 这样让p2指向s的最后一个元素
char temp; // 这里用char
while(p1<p2)
{
temp=*p1; // 要换的是指针指向的字符的值,交换指针p1,p2是不行的,实参str的值并没有改变
*p1=*p2;
*p2=temp;
p1++;
p2--;
}
return s;
}