【发布时间】:2015-02-15 21:30:37
【问题描述】:
我正在尝试交换两个 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);
}
【问题讨论】:
-
那么为什么这不起作用呢? (你一定遇到了段错误。这是有原因的。)
标签: c++