我正在尝试将一个字符串分配给一个结构值,它可以工作,但该值以某种方式链接到变量:
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;
输出是:
foo
bar
bar
bar
有人可以解释为什么会这样吗?