首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >std::string.c_str()返回一个奇怪的字符

std::string.c_str()返回一个奇怪的字符
EN

Stack Overflow用户
提问于 2013-03-16 12:56:22
回答 2查看 1.7K关注 0票数 1

在我的项目中,我使用指定它的文件名来加载纹理。现在,我创建了一个函数const char* app_dir(std::string fileToAppend);,它返回mainargv[0]并通过fileToAppend更改应用程序名称。因为我不能用char*简化字符串操作,所以我使用了std::string。我的纹理加载器使用一个const *作为文件名,因此需要切换回c_str(),现在它生成了一系列的ASCII符号字符(bug)。我已经通过将app_dir()的返回类型更改为std::string来解决这个问题。但为什么会这样呢?

编辑

样本代码:

代码语言:javascript
复制
//in main I did this

extern std::string app_filepath;

int main(int argc, char** arv) {

    app_filepath = argv[0];

    //...

}

//on other file

std::string app_filepath;

void remove_exe_name() {

    //process the app_filepath to remove the exe name

}

const char* app_dir(std::string fileToAppend) {

    string str_app_fp = app_filepath;

    return str_app_fp.append(fileToAppend).c_str();

    //this is the function the generates the bug

}

正如我前面所说的,通过将其返回类型更改为std::string,我已经有了该函数。

EN

回答 2

Stack Overflow用户

发布于 2013-03-16 13:08:03

当您使用函数、const* app_dir(std::string fileToAppend);时,您将得到指向在堆栈上分配并在函数结束时已经删除的内存的指针。

票数 1
EN

Stack Overflow用户

发布于 2013-03-16 13:23:32

返回指向本地对象的指针

代码语言:javascript
复制
return str_app_fp.append(fileToAppend).c_str();

将功能更改为

代码语言:javascript
复制
std::string app_dir(const std::string& fileToAppend) {

string str_app_fp = app_filepath + fileToAppend;

return str_app_fp;

}

在返回值上使用c_str()

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15449544

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档