一个交换字符串问题,请大家帮忙!!!
#include <stdio.h>
void swap(char **a,char **b){
char *c,e[10];
c=e;
*c=**a;
**a=**b;
**b=*c;
}
void main(){
char *p,*q,**a,**b,e[10],f[10];
p=e;q=f;
printf( "input string:\n ");
scanf( "%s %s ",p,q);
printf( "before swap:%s %s\n ",p,q);
a=&p;b=&q;
swap(a,b);
printf( "After swap:%s %s ",p,q);
getch();
}
输入:asd qwe
输出:before swap:asd qwe
After swap:qsd awe
问题出在我要输出的结果中的After swap:应该是qwe asd而不是只有改变开头字符的。麻烦大家帮帮忙,谢谢了!!!
[解决办法]
#include "conio.h "
//方法1:仅仅交换指针,字符串内容不变
void swap1(char **a,char **b)
{
char *t;
t=*a;
*a=*b;
*b=t;
}
void main()
{
char *p,*q,e[10],f[10];
p=e;q=f;
printf( "input string:\n ");
scanf( "%s %s ",p,q);
printf( "before swap:%s %s\n ",p,q);
swap1(&p,&q);
printf( "After swap:%s %s ",p,q);
getch();
}
//方法2:真正交换字符串
void swap2(char *p,char *q)
{
char buff[80];
char *pS,*pT;
pS=p;
pT=buff;
while (*pS)//copy from p to buff
*pT++ = *pS++;
*pT=0;
pS=q;
pT=p;
while (*pS)//copy from q to p
*pT++= *pS++;
*pT=0;
pS=buff;
pT=q;
while (*pS)//copy from buff to q
*pT++= *pS++;
*pT=0;
}
void main()
{
char *p,*q,e[10],f[10];
p=e;q=f;
printf( "input string:\n ");
scanf( "%s %s ",p,q);
printf( "before swap:%s %s\n ",p,q);
swap2(p,q);
printf( "After swap:%s %s ",p,q);
getch();
}