return char数组函数错误

时间:2012-08-06 19:07:18

标签: c++

  

可能重复:
  Is it a good idea to return “ const char * ” from a function?
  how to return char array in c++?

这次回归有什么问题?我正在尝试使用以下函数返回当前路径,但它似乎不正确:

请不要:我需要一个字符串返回而不是字符串。

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);

}

3 个答案:

答案 0 :(得分:4)

路径超出了函数末尾的范围,并且您将在范围外对象中返回一个内部指针。尝试返回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;
}

答案 1 :(得分:3)

当函数退出时,你返回一个超出范围的地址,因此它不再有效: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字符串和std::string非常糟糕的混合:只需使用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;
}

答案 2 :(得分:1)

该函数返回一个指向局部变量的指针,该局部变量超出范围,留下一个悬空指针。为什么不按价值返回std::string

std::string getINIfile() {
   ....
   return path;
}

然后你可以在调用方那边使用字符串的底层char*

const std::string s = getINIfile();
const char* c = s.c_str();
相关问题