Let me explain my problem
First of all, imagine I randomly generated the number "5".
I want to convert this integer to a char* so I can display it using my Draw_String() method.
I want to have "5" as the central position which would be [1] in a char* array[2].
In position [0] I want the lower adjacent number "4"
In position [2] I want the higher adjacent number "6"
so
[0] = 4 [1] = 5 [2] = 6
Then I want to display the contents of the vector positions, like this.
4
5
6
However, my output is more like this:
5
5
5
No matter what number I generate, and no matter which operations I perform, I will only get the number "5" in all of my vectors positions.
Code
int startpoint = rand() % 7 + 1;
int assigner = -1;
for (int i = 0; i < 3; i++)
{
startpoint += assigner;
convert = std::to_string(startpoint);
char *converted = &convert[0u];
blocks.push_back(converted);
assigner++;
}
//spin around twice for visual effect.
for (int counter = 0; counter < 2; counter++)
{
Draw_String(drawY, drawX - 1, blocks.at(0));
Draw_String(drawY, drawX, blocks.at(1));
Draw_String(drawY, drawX + 1, blocks.at(2));
}
if anyone could help out I'd appreciate it.
Don't ask me to get rid of char*
.
Your code has undefined behavior: it harvests a pointer to the internal string buffer from inside the conver
string
char *converted = &convert[0u];
but the buffer can become invalid the next time convert
string is re-assigned. The behavior that you see suggests that the buffer gets reused, rather than re-allocated, so the same pointer gets stored in the blocks
vector.
The best solution would be to store std::string
directly, because it would manage both copying and de-allocation for you:
std::vector<std::string> blocks;
...
blocks.push_back(std::to_string(startpoint));
If you insist on using pointers, make a copy of the string before adding it to the container:
char *copy = new char[strlen(converted)+1];
strcpy(copy, converted);
blocks.push_back(copy);
Now you are required to call delete[]
on each element of blocks
when you are done in order to avoid memory leaks.
If you needto use char* and not std::string than you need to allocate it and copy content of the string intead of copy the pointer.
instead of:
char *converted = &convert[0u];
use:
char *converted = malloc(convert.length() + 1); // number + '\0'
// can also use char *converted = new char[convert.length() + 1];
strcpy(converted, convert.c_str())
Now, no matter what happens to convert, you have control on your converted data. (take care to also delete it when you don't need it)
Otherwise when convert changes, converted can change or point to invalid data. This is because in the original implementation converted is pointing to data that is managed by convert object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.