[英]how to store and retrieve a char* from a string?
const char *RecBuffer, int *packetLength
point to the data and the size const char *RecBuffer, int *packetLength
指向数据和大小
string packet(RecBuffer,*packetLength);//store here
...do some stuff
RecBuffer = packet.c_str();//retrieve it later
now what is happening is that my Recbuffer contains lots of floats, and ints packet together which I receive as a UDP packet. 现在发生的事情是我的Recbuffer包含很多浮点数和与我一起作为UDP数据包接收的ints数据包。 But when I store and retrieve it from the string it contains garbage. 但是,当我存储并从字符串中检索它时,它包含垃圾。
Where am I going wrong? 我要去哪里错了?
I suspect the std::string
instance named packet
is being destructed, or modified, before RecBuffer
is being used, meaning RecBuffer
is a dangling pointer. 我怀疑std::string
实例名为packet
正在被破坏,或修改,之前RecBuffer
正在被使用,这意味着RecBuffer
是一个悬摆指针。 You need to copy the content of packet
rather than store a reference to an internal member of it. 您需要复制packet
的内容,而不是存储对其内部成员的引用。 Instead of dynamically allocating a char*
suggest using a std::vector<char>
(as commented by Bartek) instead: 建议不要使用std::vector<char>
(由Bartek评论)动态分配char*
而是建议:
std::vector<char> RecBuffer(packet.begin(), packet.end());
Use &RecBuffer[0]
(or RecBuffer.data()
if available, introduced in c++11) to access the internal array. 使用&RecBuffer[0]
(或c ++ 11中引入的RecBuffer.data()
如果可用))访问内部数组。
Use memcpy: 使用memcpy:
RecBuffer[packet.size()]=0;
memcpy(RecBuffer, packet.c_str(), packet.size());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.