Ive got the following code:
#include <iostream> using namespace std; int main() { char* a = "foo"; char* b = "bar"; a = b; cout << a << ", " << b << endl; return 0; }
This compiles and works, i.e. prints bar, bar . Now I would like to demonstrate that this is not copying a string. I would like to change b and show that a also changes. I came up with this simple code:
#include <iostream> using namespace std; int main() { char* a = "foo"; char* b = "bar"; a = b; b[1] = 'u'; // β just this line added cout << a << ", " << b << endl; return 0; }
... but these are segfaults. What for? Interestingly, the following modification works just fine:
#include <iostream> using namespace std; int main() { char* a = "foo"; char b[] = "bar"; // β declaration changed here a = b; b[1] = 'u'; cout << a << ", " << b << endl; return 0; }
Why is this not like the previous one? I guess I miss the important difference between pointer style and array initialization in array style.
source share