更换两个c形管柱

Exchange two c-strings

本文关键字:两个      更新时间:2023-10-16

我试图交换两个cstring的值,但不断出现错误。起初,我尝试使用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);
}

您需要一个类似std::swap:的解决方案

std::swap(s1, s2);

输出为:

s1 = Bye Bye
s2 = Hello

我想明白了,我所要做的,而不是函数交换中的一切,放:

char * temp;
temp = new char[];
temp = p1;
p1 = p2;
p2 = temp;