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

后端 未结 1 349
后悔当初
后悔当初 2021-01-29 12:33

Say I got this

char* MapIds[5000] = { \"Northeast Asia\",\"Hanyang\",\"Pusan\",\"Pyongyang\",\"Shanghai\",\"Beijing\",\"Hong Kong\", /*...5000 values etc../* };
         


        
相关标签:
1条回答
  • 2021-01-29 13:00

    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.

    0 讨论(0)
提交回复
热议问题