Pushing a variable onto a vector, value at that point in vector changes when the variable does
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
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:
std::vector<std::string> Names;
if(MyPacket.ID == 3) {Names.push_back(MyPacket.Buffer);}
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 * = 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.
std::vector<char*> Names;
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:
std::vector<std::string> Names;
There. MUCH better. You can tell your friends and family that I just saved your life.
精彩评论