2016-11-15 145 views
-1

我有以下代碼轉換字符串流爲char *

const char * getFileName(std::string filePath, std::string theDestDirectory) 
{ 
    size_t lastOfParentDirectory = filePath.find_last_of("\\"); 
    size_t extentionPos = filePath.substr(lastOfParentDirectory + 1).find_last_of("."); 
    std::stringstream convertedFilePath; 
    convertedFilePath << theDestDirectory << "\\" << filePath.substr(lastOfParentDirectory + 1).substr(0, extentionPos) << ".stl"; 
    return convertedFilePath.str().c_str(); 
} 

什麼,我試圖做的是讓新的文件路徑和更改文件的推廣。我需要的輸出是類型爲const char *的,因爲其它的處理是前人的精力在字符*

上部代碼編譯,但給一個無義輸出output

+1

'getFileName'返回一個指向本地對象內部的指針。當它返回時,返回的指針無效。 – Sergey

回答

3

convertedFilePath變量是getFileName函數內部本地。一旦函數返回,流將被破壞,並且它所持有的字符串會被破壞。這意味着您現在返回的指針指向一個已析構的字符串,並且取消引用它將導致未定義的行爲

簡單的解決方法當然是返回std::string。如果您稍後需要const char*,則可以始終在返回的對象上使用c_str函數。

2

在使用字符串之前,您只需返回一個指向對象的指針。

std::stringstream convertedFilePath; // object start living 
return convertedFilePath.str().c_str(); // return pointer to inside the object 
} // the object convertedFilePath is dead and the memory is not longer usable 

可能的解決方案:

  1. 返回對象本身(convertedFilePath)
  2. 生成前的對象,並把它作爲參考的功能
  3. 一個指針傳遞給一個char *,其中它指向的內存足夠大 並將convertedFilePath.c_str()的內容複製到 之前的區域中您的函數結束