问题
Say I got this
char* MapIds[5000] = { "Northeast Asia","Hanyang","Pusan","Pyongyang","Shanghai","Beijing","Hong Kong", /*...5000 values etc../* };
I tried
strcpy(MapIds[0], "gfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg");
But it crashes
How Do I keep changing them around without messing up the strings in other elements.
I dont want to use std::string or vector those cause crazy slow compile times.
回答1:
Because you try to copy into a literal string ("Northeast Asia"
).
In C++ a literal string is really a constant array of characters, any attempt to modify such an array will lead to undefined behavior (which can sometimes express themselves as crashes).
If you want to make MapIds[0]
point to a new string, then you simply use assignment:
MapIds[0] = "gfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg";
Because literal strings are constant arrays of characters, C++ doesn't really allow you to have a char*
to point to them, you must use const char*
:
const char* MapIds[] = { ... };
However, a much better solution is to not use C-style strings and char
pointers (const
or not) at all, but only use std::string
:
std::string MapIds[] = { ... };
Then you can modify the strings in the array itself, using plain assignment as shown above.
来源:https://stackoverflow.com/questions/60501901/c-how-to-populate-a-static-array-of-strings-with-new-strings-in-different-loca