[Solved] Swapping two strings in C++


What does the arguments (char * &str1, char * &str2) specify in the swap function?

they specify that parameters are of type reference to pointer to char. This means that function might change the value of the variable that was provided as argument to this function.

What if they are replaced by (char &str1, char &str2) and char *temp=str1 with char &temp=str1 inside the swap function?

then you will get compiler error, because you will still call it like: swap(str1, str2);, you would have to change the call to swap(*str1, *str2); and then you will swap first letter of both strings.

[edit]

Your code includes also another subtle error, you use using namespace std; which causes std::swap to be called when you change your swap function signature to void swap(char &str1, char &).

You should also see warnigs like:

main.cpp:17:14: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wpedantic]
char *str1 = “GEEKS”;

this is because string literals are const pointers, otherwise you introduce UB in your code. You should change to const char *str1

6

solved Swapping two strings in C++