0

我正在尝试将一个字符串分配给一个结构值,它可以工作,但该值以某种方式链接到变量:

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

有人可以解释为什么会这样吗?

4

1 回答 1

2
struct test_struct{
    const char *server, *user; 
};
test_struct test;

好的,test.server指针也是如此。

test.server = tmp.c_str(); // 1
cout << test.server << endl; // 2

tmp = "bar"; // 3
test.user = tmp.c_str();
cout << test.user << endl;

cout << "" << endl;

cout << test.server << endl; // 4

在 1 中,您设置test.server指向的内容tmp。在2中,您输出test.server指向的内容,这很好。

3、修改内容tmp。所以现在,test.server指向一些不再存在的东西—— tmp.

4、你输出什么test.server指向。但那是tmp你在 3 中销毁的 back at 1 的内容。

你不能输出你删除的东西。

于 2021-11-16T23:19:00.113 回答