2013-03-16 52 views
0

在我的項目,我使用通過指定文件名來加載紋理。現在,我做了這個功能const char* app_dir(std::string fileToAppend);,返回main小號argv[0]並通過fileToAppend更改應用程序的名稱。由於我無法使用char *輕鬆進行字符串操作,因此我使用std::string。我的紋理加載器需要一個const char *作爲文件名,所以需要切換回c_str(),現在它會生成一串ASCII符號字符(bug)。我已經通過將app_dir()的返回類型更改爲std::string來解決此問題。但爲什麼會發生?的std :: string.c_str()返回一個奇怪的字符

編輯

示例代碼:

//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的功能之一。

+0

你能通過發佈有關代碼來澄清你的問題嗎? – 2013-03-16 13:07:06

+0

請提供你的代碼,它會導致它容易根從現在讀碼 – 2013-03-16 13:07:49

+0

@Telkitty看看我的編輯。 – mr5 2013-03-16 13:20:20

回答

0

當你使用功能爲const char * APP_DIR(的std :: string fileToAppend);你得到的指針指向堆棧上分配的內存,並且在函數結束時已經被刪除。

+0

我用像'PNG_LoadTexture(APP_DIR( 「圖片\\ backgroun1.png」),...)的一些功能'app_dir';' – mr5 2013-03-16 13:21:51

0

一個很大的不,不:)返回指向本地對象

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

你的函數改爲

std::string app_dir(const std::string& fileToAppend) { 

string str_app_fp = app_filepath + fileToAppend; 

return str_app_fp; 

}

,而在返回值使用c_str()

+0

是的,我是這樣做也。但是你能解釋一下,爲什麼'const char *'的返回類型在返回一個'std :: string.c_str();'後做了一些錯誤。 – mr5 2013-03-16 13:30:44

+1

當然,在你原來的代碼,你宣佈在棧上本地的std :: string對象,確實有些記憶是_dynamically_以保持附加路徑分配的,但是當函數返回的std :: string析構函數被調用,所有的分配內存被釋放,你離開W /一個失速指針釋放內存區域,因此你看到垃圾 – 2013-03-16 13:37:14

+0

好吧,謝謝! – mr5 2013-03-16 13:42:01