[英]C++ stringstream to char* conversion memory allocation
誰能解釋以下代碼是如何工作的,並且不會使應用程序崩潰?
int main() {
char *tempStr = new char[5];
tempStr[0] = '\0';
string stemp = "helloworld";
stringstream sstream;
sstream.str(stemp);
cout << "len before = " << strlen(tempStr);
sstream >> tempStr;
cout << "len after = " << strlen(tempStr) << endl;
cout << tempStr << endl;
delete[] tempStr;
return 1;
}
我得到的輸出為
len before = 0
len after = 10
helloworld
stringstream
在字符指針多余的字符分配內存? char*
分配的內存的情況下將數據從stringstream
復制到char *數組的正確方法嗎? 字符串流是否為char指針中的多余字符分配了內存?
否。您的代碼會調用未定義的行為。
還想知道在不超出為char *分配的內存的情況下將數據從stringstream復制到char *數組的正確方法嗎?
讀入char*
不是一個好主意。 使用std::string
從流中讀取輸入。 但是,如果您仍然想為了知識而知道,請使用std::istream::read()
。
if ( sstream.read(tempStr, 5 ) )
{
//read succeeded
}
順便說一句,您可以合並這兩行:
stringstream sstream;
sstream.str(stemp);
合為一:
stringstream sstream(stemp);
或者只是這樣:
stringstream sstream("helloworld"); //no need of stemp!
希望能有所幫助。
char
數組。 在C ++中,手動執行此操作毫無意義。 只需使用std::string
完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.