I am trying to write a swap function, which will swap data of 2 pointers. I get segmentation fault error. Can someone help, please?
P.S. I know that string class has built in swap function but I am trying to learn how pointers work.
#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;
}