C ++如何在不同位置用新字符串填充字符串的静态数组? [英] C++ How to populate a static array of strings with new strings in different locations?

查看:70
本文介绍了C ++如何在不同位置用新字符串填充字符串的静态数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我明白了

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

我尝试过

strcpy(MapIds[0], "gfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg");

但是它崩溃了

我该怎么办不断更改它们而不会弄乱其他元素中的字符串。

How Do I keep changing them around without messing up the strings in other elements.

我不想使用std :: string或vector导致疯狂的缓慢编译时间。

I dont want to use std::string or vector those cause crazy slow compile times.

推荐答案

因为您尝试将其复制为文字字符串(东北亚 )。

Because you try to copy into a literal string ("Northeast Asia").

在C ++中,文字字符串实际上是字符的 恒定数组,任何尝试修改此类数组的尝试都会导致未定义的行为(有时可能会表示为崩溃)。

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).

如果您想创建 MapIds [0 ] point 指向一个新字符串,然后只需使用赋值即可:

If you want to make MapIds[0] point to a new string, then you simply use assignment:

MapIds[0] = "gfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg";






因为文字字符串是恒定的字符数组,所以C ++并没有真正允许您使用 char * 指向它们,您必须使用 const char *


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[] = { ... };

但是,更好的解决方案是不使用C样式字符串和 char 指针(是否使用 const ),但仅使用 std :: string

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.

这篇关于C ++如何在不同位置用新字符串填充字符串的静态数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆