我试图交换两个cstrings的值,但我一直在犯错误。起初我尝试使用for循环来单独交换每个数组中每个元素的值,但现在我尝试使用strcpy()函数。我不知道自己做错了什么。非常感谢任何帮助!
#include <iostream>
using namespace std;
void exchange(char * &, char * &);
int main()
{
char * s1 = "Hello";
char * s2 = "Bye Bye";
exchange(* & s1, * & s2);
cout << "s1 = " << s1 << endl; //"Bye Bye" should be displayed
cout << "s2 = " << s2 << endl; // "Hello" should be displayed
return 0;
}
void exchange(char * & p1, char * & p2)
{
int size;
if (strlen(*& p2) > strlen(*& p1))
{
size = strlen(*& p2);
}
else
{
size = strlen(*& p1);
}
char * temp;
temp = new char[size];
strcpy(*&temp, *&p1);
strcpy(*&p1, *&p2);
strcpy(*&p2, *&temp);
}
答案 0 :(得分:0)
答案 1 :(得分:-2)
我想通了,我只需要做,而不是功能交换中的所有内容,放:
char * temp;
temp = new char[];
temp = p1;
p1 = p2;
p2 = temp;