定义两个指针分别指向“how are you.”和“I am fine.”;定义一个交换函数,完成两个指针的交换。

这哪里错了呢?麻烦改改啊。跪谢!
#include<iostream.h>
char swap(char*,char*);
void main()
{
char a[15]="How are you?",b[15]="I am fine.";
cout<<a<<" "<<b<<endl;
swap(&a,&b);
cout<<"after swapping..."<<endl;
cout<<a<<" "<<b<<endl;
}
void swap(char* x,char* y)
{
char temp= *x;
*x= *y;
*y= *temp;
}

直接定义两个字符串指针就行了,用数组的话,得另外定义指针来指向这两个数组,然后交换指针,数组一旦定义好,是不能修改它指向的地址的,所以,也不能直接交换两个数组。

#include <iostream>//注意这里不需要.h

using namespace std;

void swap(char**,char**);//参数应该是指向指针的指针,这样才能完成实参的交换,在C++里也可以使用指针引用char *&p 

void swap2(char*&x,char*&y);//c++里使用指针引用

 

void main()

 char *a="How are you?";

 char *b="I am fine."; 

 cout<<a<<"   "<<b<<endl; 

 swap(&a,&b); //调用指向指针的指针的函数

//swap2(a,b); //调用指针引用函数

 cout<<"after swapping..."<<endl; 

 cout<<a<<"   "<<b<<endl;

//使用指向指针的指针作为参数

void swap(char**x,char**y) 

{

 //完成指针所指向内容的交换 

 char **temp= x; 

 *x= *y; 

 *y= *temp;

}

 

//使用指针引用作为参数

void swap2(char*&x,char*&y)

{

 char *temp= x; 

 x= y; 

 y= temp;

 

结果如下:

 

 

 

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-01-06
说明两点:
1、想通过另一个函数实现两个指针值的交换,建议传入指针的指针;
2、数组和指针是有区别的,建议定义a和b时,将它们定义为指针而不是数组,这样便于修改指针的值。

void main()
{
char *a="How are you?";
char *b="I am fine.";
cout << a << " " << b << endl;
swap(a,b);
cout << "after swapping..." << endl;
cout << a << " " << b << endl;

return 0;
}

void swap(char **x,char **y)
{
char *temp = *x;
*x = *y;
*y = temp;
}
第2个回答  2013-01-06
这样改:

#include<iostream.h>

void swap(char**,char**); //这里

int main()
{
char *a = "How are you?", *b = "I am fine."; //这里
cout<<a<<" "<<b<<endl;

swap(&a, &b);
cout<<"after swapping..."<<endl;
cout<<a<<" "<<b<<endl;
return 0;
}
void swap(char** x,char** y) //这里
{
char *temp= *x; //这里
*x = *y;
*y= temp; //这里
}
第3个回答  2013-01-06
你把你的问题发在英语翻译里面了……
现在输出的结果是什么?是经过了swap过程之后还是没有交换吗?还是输出有一个为空?不熟悉C语言啊。
如果有一个是输出为空的话,那就应该是最后这里 *y=*temp应该为*y=temp
第4个回答  2013-01-06
/*
How are you? I am fine.
after swapping...
I am fine. How are you?
Press any key to continue
*/
#include <iostream.h>
#include <cstring>
void swap(char *,char *);
int main() {
char a[15] = "How are you?",b[15] = "I am fine.";
cout << a << " " << b << endl;
swap(a,b);
cout << "after swapping..." << endl;
cout << a << " " << b << endl;
return 0;
}

void swap(char *x,char *y) {
char temp[15];
strcpy(temp,x);
strcpy(x,y);
strcpy(y,temp);
}本回答被提问者采纳

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网