Swapping 2 string vars.

I'm making a small library for my own use.

Although I'm feeling quite stupid as I'm beeing defeated by string pointers.

1
2
3
4
5
6
7
void swap(char *a, char *b)
{
    char *temp;
    temp=a;
    a=b;
    b=temp;
}


swap() has having no effect.

1
2
3
4
5
6
7
8
char *c1="Hello";
char *c2="Goodbye";

cout<<c1<<c2; //1

swap(c1,c2);

cout<<c1<<c2; //2 


Output 1 = Output 2 instead of beeing in the inverse order as I'd expect them.

What am I doing wrong?

Thank's,

Hugo Ribeira
You need to pass the pointers by reference, otherwise you'd only be changing them inside the function.
void swap(char *&a, char *&b)
http://www.cplusplus.com/doc/tutorial/functions2/

Also, you need to have those as const char * because they point to constant characters (string literals)
Last edited on
Thank's, I thought that pass by reference was only used with "regular" variables.
Pointers are 'regular' variables. In fact, I can't really think of any variables or classes that aren't 'regular'.
Topic archived. No new replies allowed.