这次退货有什么问题吗?我试图使用以下函数返回当前路径,但似乎不正确:
请不要:我需要一个字符,还不是字符串。
char* getINIfile(void)
{
char buffer[MAX_PATH];
GetModuleFileName( NULL, buffer, MAX_PATH );
string::size_type pos = string( buffer ).find_last_of( "\\/" );
string path = string( buffer ).substr( 0, pos) + "\\setup.ini";
char *ini_local= (char*)path.c_str();
printf(ini_local); // so far output OK!
return ini_local;
}
main
{
printf(getINIfile()); // output Not OK!
char mybuffer[200];
GetPrivateProfileStringA( "files","DLL","0", mybuffer,200, getINIfile());
printf(mybuffer);
}发布于 2012-08-06 19:08:28
当函数退出时,您将返回超出作用域的地址,因此它不再有效:std::string path是函数getINIFile的本地地址,因此在函数退出后它是无效的,从path.c_str()获得的地址也是无效的。
在这种情况下,您可以从函数中返回std::string。如果以后确实需要一个C字符串,那么可以使用c_str():
std::string getINIfile(void)
{
//...
return path;
}
int main()
{
string path = getINIFile();
// do something with path.c_str():
const char *cPath = path.c_str();
}考虑到您的代码,我想不出您必须有一个char*返回的任何原因,但是如果是这样的话,您需要在堆上分配一个缓冲区:
char *getINIfile(void)
{
char *buffer[MAX_PATH];
GetModuleFileName(NULL, buffer, MAX_PATH);
string::size_type pos = string(buffer).find_last_of( "\\/" );
string path = string(buffer).substr( 0, pos) + "\\setup.ini";
char *ini_local = new[path.size()];
strncpy(ini_local, path.c_str(), path.size());
printf(ini_local); // so far output OK!
return ini_local;
}但是这是一个非常糟糕的混合标准C字符串和的:只是使用string操作路径,然后在其他地方传递char*。
只使用标准C,将find_last_of替换为strrchr --注意缺少错误处理:
char *getINIfile(void)
{
char *buffer = new[MAX_PATH];
char *pos = NULL;
char *ini_local = NULL;
GetModuleFileName(NULL, buffer, MAX_PATH);
pos = strrchr(buffer, "\\/");
// check for and handle pos == NULL
buffer[pos] = '\0';
strncat(buffer, "\\setup.ini", MAX_PATH - strlen(buffer));
printf(buffer);
return buffer;
}发布于 2012-08-06 19:09:48
path在函数结束时超出作用域,您将在超出作用域对象中返回一个内部指针。尝试返回一个std::string
std::string getINIfile(void)
{
char buffer[MAX_PATH];
GetModuleFileName( NULL, buffer, MAX_PATH );
string::size_type pos = string( buffer ).find_last_of( "\\/" );
string path = string( buffer ).substr( 0, pos) + "\\setup.ini";
char *ini_local= (char*)path.c_str();
printf(ini_local); // so far output OK!
return path;
}发布于 2012-08-06 19:08:38
函数正在返回一个指向局部变量的指针,该局部变量超出了作用域,留下了一个悬空指针。为什么不按值返回一个std::string呢?
std::string getINIfile() {
....
return path;
}然后,只需在调用方使用字符串的底层char*:
const std::string s = getINIfile();
const char* c = s.c_str();https://stackoverflow.com/questions/11834316
复制相似问题