Below code gives me a compilation error, but I don’t understand what I am doing wrong. Sorry about asking such a silly question.
$ cat swapcstrings.cc
#include <iostream>
void swap(char*& c, char*& d) {
char* temp = c;
c = d;
d = temp;
}
int main() {
char c[] = "abcdef";
char d[] = "ghijkl";
std::cout << "[" << c << "," << d << "]\n";
swap(c, d);
std::cout << "[" << c << "," << d << "]\n";
}
$ g++ swapcstrings.cc
swapcstrings.cc: In function ‘int main()’:
swapcstrings.cc:13: error: invalid initialization of non-const reference of type ‘char*&’ from a temporary of type ‘char*’
swapcstrings.cc:3: error: in passing argument 1 of ‘void swap(char*&, char*&)’
$
Arrays cannot be modified, and they merely decay to temporary pointers, they are not really pointers and cannot be swapped. The address of an array cannot be changed, and the compiler errors when you try to bind the temporary pointer you got from the array to a non-
constreference, which is against the rules of the language.Declare the arrays, then swap two pointers to them.
Or if you can change the prototype of the function, use
const char*in the first place: