Yhlas
Yhlas

Reputation: 421

Swap data of pointers in C++

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;

}

Upvotes: 0

Views: 291

Answers (1)

ashiquzzaman33
ashiquzzaman33

Reputation: 5741

You can use swap function as

void swap(char **s1, char **s2){

    char *temp = *s1;
    *s1 = *s2;
    *s2 = temp;
}

And call this function as

 swap(&s1, &s2);

If you use c++ you can use reference version suggested by BLUEPIXY

void swap(const char *&s1, const char *&s2)
{
    const char *temp = s1;
    s1 = s2;
    s2 = temp;
}

Upvotes: 4

Related Questions