I'm trying to assign a string to a struct value, which works, but the value somehow links to the variable:
string tmp;
struct test_struct{
const char *server, *user;
};
test_struct test;
tmp = "foo";
test.server = tmp.c_str();
cout << test.server << endl;
tmp = "bar";
test.user = tmp.c_str();
cout << test.user << endl;
cout << "" << endl;
cout << test.server << endl;
cout << test.user << endl;
The output is:
foo
bar
bar
bar
Can someone please explain why this is happening?
Okay, so
test.serveris a pointer.In 1, you set
test.serverto point to the contents oftmp. In 2, you output whattest.serverpoints to, which is fine.In 3, you modify the contents of
tmp. So now,test.serverpoints to something that no longer exists -- the former contents oftmp.In 4, you output what
test.serverpoints to. But that was the contents oftmpback at 1, which you destroyed in 3.You cannot output something that you obliterated.