[英]C++ stringstream to char* conversion memory allocation
Can anyone explain how the following code is working and does not crash the application? 谁能解释以下代码是如何工作的,并且不会使应用程序崩溃?
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;
}
I am getting the output as 我得到的输出为
len before = 0
len after = 10
helloworld
stringstream
allocate memory for the extra characters in the char pointer? 难道stringstream
在字符指针多余的字符分配内存? stringstream
to char* array, without exceeding the memory allocated for char*
? 还想知道在不超出为char*
分配的内存的情况下将数据从stringstream
复制到char *数组的正确方法吗? Did stringstream allocate memory for the extra characters in the char pointer? 字符串流是否为char指针中的多余字符分配了内存?
No. Your code invokes undefined behavior. 否。您的代码会调用未定义的行为。
Also want to know the correct way to copy data from stringstream to char* array, without exceeding the memory allocated for char*? 还想知道在不超出为char *分配的内存的情况下将数据从stringstream复制到char *数组的正确方法吗?
It is not a good idea to read into char*
. 读入char*
不是一个好主意。 Use std::string
to read input from stream. 使用std::string
从流中读取输入。 But then if you still want to know for the sake of knowledge, use std::istream::read()
. 但是,如果您仍然想为了知识而知道,请使用std::istream::read()
。
if ( sstream.read(tempStr, 5 ) )
{
//read succeeded
}
By the way, you can merge these two lines: 顺便说一句,您可以合并这两行:
stringstream sstream;
sstream.str(stemp);
into one: 合为一:
stringstream sstream(stemp);
or simply this: 或者只是这样:
stringstream sstream("helloworld"); //no need of stemp!
Hope that helps. 希望能有所帮助。
char
array if it runs out of space. 您将必须逐块进行处理,如果空间不足,请重新分配char
数组。 In C++, there's little point in doing this manually. 在C ++中,手动执行此操作毫无意义。 Just use std::string
and be done. 只需使用std::string
完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.