c++ - 意外链接 c_str() 字符串
问题描述
我正在尝试将一个字符串分配给一个结构值,它可以工作,但该值以某种方式链接到变量:
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
有人可以解释为什么会这样吗?
解决方案
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 的内容。
你不能输出你删除的东西。
推荐阅读
- javascript - 通过表单输入更新状态
- ios - UIImage view matrix transform in iOS
- c# - How to update my record value sql in webservice
- google-cloud-dataflow - 在 Apache Beam 中使用 BigTable 中的 checkAndMutate(条件写入)
- react-native - 世博模拟器未在设备上打开
- c++ - 从字符串转换为 double 和 int - C++
- docker - ASP .NET Core 在 Heroku 上给出 System.Net.Sockets.SocketException 错误
- c++ - 我们应该在使用 std::bind 之前检查一个不为空的函数吗?
- php - 通过反射类调用 Eloquent 方法,找不到方法错误
- python - 获取 OSError: [WinError 193] %1 不是带有 anaconda 和 jupyter 的有效 Win32 应用程序