c++简单指针问题,有偿,请诸君解决

编写函数SwapCharPointer()实现交换两个字符型指针的值的功能。例如,已知“char *s1="teacher";char *s2="student";”,执行“SwapCharPointer(&s1,&s2);”或“SwapCharPointer(s1,s2);”后s1指向字符串“student”的首地址,s2指向字符串“teacher”的首地址。 程序会输入两个字符串s1,s2;在进行调换后输出调换后的s1,s2

Sample Input 0

student
teacher

Sample Output 0

teacher
student

用指针的指针的话,直接交换指针地址即可

#include <iostream>
using namespace std;
void SwapCharPointer(char** s1, char** s2) {
    char* temp = *s1;
    *s1 = *s2;
    *s2 = temp;
}
int main() {
    char s1[100],s2[100],*p = s1,*q=s2;
    cin.getline(p,100);
    cin.getline(q,100);
    SwapCharPointer(&p, &q);
    cout << p << endl; 
    cout << q << endl; 
    return 0;
}

#include <iostream>
#include <cstring>

using namespace std;

void SwapCharPointer(char** s1, char** s2) {
    // Store the value of s1 in a temporary variable
    char* temp = *s1;

    // Assign the value of s2 to s1
    *s1 = *s2;

    // Assign the value of the temporary variable (which was the original value of s1) to s2
    *s2 = temp;
}

int main() {
    char* s1 = "teacher";
    char* s2 = "student";

    // Swap the values of s1 and s2
    SwapCharPointer(&s1, &s2);

    cout << s1 << endl;  // Outputs "student"
    cout << s2 << endl;  // Outputs "teacher"

    return 0;
}

详细实现的代码和运行结果如下,望采纳

#include <iostream>
using namespace std;

void SwapCharPointer(char *&s1, char *&s2) {
  // 定义一个临时指针变量
  char *temp = s1;

  // 交换两个指针的值
  s1 = s2;
  s2 = temp;
}

int main() {
  char *s1 = "teacher";
  char *s2 = "student";

  cout << "s1: " << s1 << endl;
  cout << "s2: " << s2 << endl;

  SwapCharPointer(s1, s2);

  cout << "s1: " << s1 << endl;
  cout << "s2: " << s2 << endl;

  return 0;
}

输出结果如下:

s1: teacher
s2: student
s1: student
s2: teacher

#include <iostream>
#include <cstring>

using namespace std;


//用指针写swap()函数
void swap_1(char** p1,char** p2){
    char* temp = *p1;
    *p1 = *p2;
    *p2 = temp;
} 

int main(){
    char* a = "teacher";
    char* b = "student";
    
    swap_1(&a,&b);
    
    cout << a << endl;  
    cout << b << endl;
    return 0;
}

#include<iostream>

using namespace std;

void SwapCharPointer(char** s1, char** s2)
{
    char* temp = *s1;
    *s1 = *s2;
    *s2 = temp;
}

int main()
{
    char* s1 = (char*)"teacher";
    char* s2 = (char*)"student";
    SwapCharPointer(&s1, &s2);
    cout << s1 << endl;
    cout << s2 << endl;

    return 0;
}

vs2019测试可通过