康斯特查尔..改变
Const char... changed?
这是我简单程序的一部分
string appData = getenv("APPDATA");
const char *mypath= (appData+"\MyApplication\hello.txt").c_str();
cout << mypath;
// output: c:usersxrobotappdataRoamingMyapplicationhello.txt
fstream file(mypath,ios::in);
ofstream filetemp;
filetemp.open("world.bak");
cout << mypath;
// output: É↕7
为什么我的路径在那个奇怪的字符串中发生了变化?
您应该将std::string
用作:
std::string appData = getenv("APPDATA");
std::string path = appData+"\MyApplication\hello.txt";
然后这样做:
const char * mypath = path.c_str();
请注意,您不得这样做:
const char* mypath = (appData+"\MyApplication\hello.txt").c_str();
这是因为右侧的表达式是临时的,在表达式结束时被销毁,mypath
将继续指向被破坏的对象。换句话说,它变成了一个悬而未决的指针。
--
为什么我的路径在那个奇怪的字符串中发生了变化?
因为在你发布的代码中,mypath
是一个悬而未决的指针,使用它调用未定义的行为。
这是您应该如何编写代码:
std::string appData = getenv("APPDATA");
std::string mypath= appData+"\MyApplication\hello.txt";
cout << mypath;
fstream file(mypath.c_str(),ios::in);
你不能像这样添加两个字符串。 您应该会收到明确的警告。 由于您使用的是C++,因此可能需要改用std::string
。
这只是
一个临时std::string
:
(appData+"\MyApplication\hello.txt")
因此,可以在使用表达式后释放基础 C 字符串空间。由于您有一个指向现在垃圾内存的char*
,因此您有一个时髦的值。
相关文章:
- 康斯特指针C++斯特劳斯特鲁普
- Static_cast 对于康斯特来说,会抛弃预选赛
- 东康斯泰克普/康斯蒂尼特/康斯特瓦尔在C++20 中允许吗?
- 康斯特正确性建议
- 从字符到康斯特* 字符的转换无效,代码有什么问题?
- T*上的部分排序...和康斯特·
- 调用"树:<int>:运算符==(树*&<int><int>,树*&)康斯特"没有匹配函数
- 抛弃康斯特,就是这种定义明确的行为
- 错误:类型为 '.&' 来自类型的临时 '..*康斯特'
- 无法push_back移动(不可复制与康斯特字段)到矢量
- 传递康斯特字符*的值
- mpg123_open()和康斯特
- 康斯特指针浅拷贝
- C++ wifstream:不兼容的字符常量*,wchar_t康斯特*类型
- 康斯特是谎言吗?(因为康斯特可以被抛弃)
- 康斯特·查尔 * 变得腐败
- 康斯特查尔..改变
- 康斯特与 #define(奇怪的行为)
- 这是抛弃康斯特吗?
- 第二个康斯特在"const int const &someval"做什么?