康斯特查尔..改变

Const char... changed?

本文关键字:改变 康斯特      更新时间:2023-10-16

这是我简单程序的一部分

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*,因此您有一个时髦的值。