-2

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.

SSpoke
  • 5,656
  • 10
  • 72
  • 124

1 Answers1

5

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 2
    As a supplement, using `char*` to point to a string literal is wrong. – con ko Mar 03 '20 at 07:46
  • how do I get a `c_str()` into the array at some element? – SSpoke Mar 03 '20 at 08:09
  • without `char*` I get `Error C2078 too many initializers` `Error E0146 too many initializer values` – SSpoke Mar 03 '20 at 08:11
  • `std::string` with 5000 strings takes like 40 seconds to compile though and the `char* MapIds[] = {}` only takes like 2-3 seconds. thats why I dont want to use `std::string` – SSpoke Mar 03 '20 at 08:20
  • @SSpoke it works for me: https://godbolt.org/z/8PqCA7 are you sure you have no more than 5000 strings in your initialiser? Adding an additional string to the linked code reproduces the `too many initializers` error – Alan Birtles Mar 03 '20 at 08:28
  • @SSpoke To be honest, if you have 5000 strings in the code itself, you're not doing it right (IMO). I would simply have the strings in a simple text-file, one string per line. Then use `while (std::getline(file, input))` and add each string to a `std::vector`. Compile-time should be even faster than what you have now, and the extra run-time needed should be minimal even with a slow disk. Especially if you do it only once. – Some programmer dude Mar 03 '20 at 09:09
  • @SSpoke And depending on the problem and use-case, maybe you should even consider using a database? Especially if you want to make changes and have them be saved. – Some programmer dude Mar 03 '20 at 09:11