我正在尝试编写一个交换函数,它将交换 2 个指针的数据。我收到段错误错误。有人可以帮忙吗?
附言我知道字符串类内置了交换函数,但我正在尝试学习指针的工作原理。
#include<iostream>
#include<cstring>
using namespace std;
void swap(char *, char *);
int main(){
char *s1="blah";
char *s2="crap";
swap(s1, s2);
cout<<s1<<endl<<s2<<endl;
return 0;
}
void swap(char *s1, char *s2){
char *t1 = new char[strlen(s1)+1];
char *t2 = new char[strlen(s2)+1];
for(int i=0; i<=strlen(s1); i++){
t1[i] = s1[i];
}
for(int i=0; i<strlen(s2); i++){
t2[i] = s2[i];
}
cout<<*t1<<endl;
cout<<*t2<<endl;
*s1 = *t2;
*s2=*t1;
}
最佳答案
你可以使用swap
函数作为
void swap(char **s1, char **s2){
char *temp = *s1;
*s1 = *s2;
*s2 = temp;
}
并将此函数称为
swap(&s1, &s2);
如果您使用c++
,您可以使用BLUEPIXY建议的引用版本
void swap(const char *&s1, const char *&s2)
{
const char *temp = s1;
s1 = s2;
s2 = temp;
}
关于c++ - 在 C++ 中交换指针的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36906994/