c++ 交换字符串问题

来源:百度知道 编辑:UC知道 时间:2024/05/17 16:07:21
请帮我看看下面的这个程序错在哪了?
#include<iostream.h>
#include<string.h>

void swap(char *x,char *y)
{
char temp[20];
strcpy(temp,x);
strcpy(x,y);
strcpy(y,temp);
}

void main()
{
char *ap="hello";
char *bp="how are you?";
cout<<"ap:"<<ap<<endl;
cout<<"bp:"<<bp<<endl;
swap(ap,bp);
cout<<"swap ap,bp"<<endl;
cout<<"ap:"<<ap<<endl;
cout<<"bp:"<<bp<<endl;
}

/*
你定义的那两个ab,bp,这里ab的长度小于bp的,所以在strcpy(x,y)时出现错误~同时strcpy(y,temp)也一样~bp的长度小于temp所以不行.
*/
#include<iostream.h>
#include<string.h>

void swap(char *x,char *y)
{
char temp[20];
strcpy(temp,x);
strcpy(x,y);
strcpy(y,temp);
}

void main()
{

char ap[20]="hello";
char bp[20]="how are you?";
cout<<"ap:"<<ap<<endl;
cout<<"bp:"<<bp<<endl;
swap(ap,bp);
cout<<"swap ap,bp"<<endl;
cout<<"ap:"<<ap<<endl;
cout<<"bp:"<<bp<<endl;
}

void swap(char *x,char *y)
{
char temp;
while(*x!=''||*y!='')
{

temp=*x;
*x=*y;
*y=temp;
x++;
y++;
}
}
main()
{
char a[20] = "hello";
char b[20] = "ho