将变量推入向量,向量中该点的值会随着变量的变化而改变
我有一个编程问题 =)
std::vector<char*> Names;
if(MyPacket.ID == 3) {Names.push_back(MyPacket.Buffer);}
我将接收到的缓冲区推送到向量上,就像这样,但是当缓冲区发生变化时,向量中该点的变量值也会发生变化。
假设我发送并推送了一个包含“Simon”的缓冲区到向量上,这样就可以了,因此向量上的点 [0] 处将是单词 Simon。
但是当我收到一个新的缓冲区时,它会覆盖位置 [0],即使数据包 ID 不同,这个新缓冲区也不会到达 if 语句中的断点。
我真的希望我能够很好地解释这一点,我尝试询问朋友的建议,他向我推荐了这个网站。
任何帮助都会感谢
大卫·安德鲁斯
I have a programming problem =)
std::vector<char*> Names;
if(MyPacket.ID == 3)
{Names.push_back(MyPacket.Buffer);}
I push the recieved buffer onto a vector like so, but when the buffer changes so does the value of the variable at that point in the vector.
So say I sent and pushed a buffer containing 'Simon' onto the vector that would be fine so at point [0] on the vector would be the word Simon.
but then when I recieve a new buffer it overwrites position [0] even though the packets ID is different, a breakpoint within the if statement is not reached with this new buffer.
I really hope i'm explaining this well enough, I tried asking a friends advice and he pointed me towards this site.
Any help appreciated
David Andrews
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在将指针推送到内存中的某些字符,如果该指针指向的区域发生变化,那么您将看到更改后的值。如果您希望复制缓冲区的值,您可以使用 std::string 向量而不是 char* 向量。
例如:
如果缓冲区包含以 null 结尾的字符串。如果没有,您将需要从某处获取缓冲区的长度,并创建一个从 buffer 到 buffer+len 的字符串。
You are pushing a pointer to some characters in memory, if the area where this pointer points changes then you will see the changed value. If you wish to copy the value of the buffer you can probably use a vector of std::string instead of a vector of char*.
For example:
if the buffer contains a null-terminated string. If not, you will need to get the length of the buffer from somewhere and create a string from buffer to buffer+len.
char * = 指向 char 的地址。
我假设 MyPackey.Buffer 也是 char*。
如果是这样,那么您将 Buffer 的地址推送到向量上,因此 Buffer 和 Names[0] 具有相同的值(例如 [0x10223943])。
您需要执行 memcopy 或类似的操作,将内存地址 MyPacket.Buffer 处的值复制到新内存中,然后使用它。
简单示例 http://www.cplusplus.com/reference/clibrary/cstring/memcpy/希望
这有帮助。
char * = address pointing to char.
I am assuming that MyPackey.Buffer is also char*.
If so then you are pushing the address of Buffer onto the vector, so both Buffer and Names[0] have the same value ([0x10223943] for example).
You need to do a memcopy or something like that to copy the values at memory address MyPacket.Buffer into new memory and then use that.
Simple example http://www.cplusplus.com/reference/clibrary/cstring/memcpy/
Hope this helps.
不,不,不,不,不!只要说“不”!所有的问题以及更多的问题都在这个小小的变量声明中。让我为你解决这个问题:
在那里。好多了。你可以告诉你的朋友和家人我刚刚救了你的命。
No, no, no, no, NO! Just say NO! All of your problems and a whole lot more are right there in that one little variable declaration. Let me fix that for you:
There. MUCH better. You can tell your friends and family that I just saved your life.