C++ How to populate a static array of strings with new strings in different locations?

时光毁灭记忆、已成空白 提交于 2021-02-05 12:28:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!