使用 c_str() 设置字符数组?
char el[3] = myvector[1].c_str();
myvector[i]
是一个包含三个字母的字符串。为什么会出现这个错误?
char el[3] = myvector[1].c_str();
myvector[i]
is a string with three letters in. Why does this error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
它返回 char* 类型,它是一个指向字符串的指针。您不能将其直接分配给这样的数组,因为该数组已经分配了内存。尝试:
但是如果字符串本身被破坏或更改,请务必小心,因为指针将不再有效。
It returns type char* which is a pointer to a string. You can't assign this directly to an array like that, as that array already has memory assigned to it. Try:
But very careful if the string itself is destroyed or changed as the pointer will no longer be valid.
因为
const char *
不是数组的有效初始值设定项。更重要的是,我相信 c_str 返回一个指向内部存储器的指针,因此存储起来不安全。您可能想以某种方式复制该值(
memcpy
或std::copy
或其他方式)。Because a
const char *
is not a valid initializer for an array. What's more, I believec_str
returns a pointer to internal memory so it's not safe to store.You probably want to copy the value in some way (
memcpy
orstd::copy
or something else).除了其他人所说的之外,请记住,长度为三个字符的字符串在转换为 c_str 时需要四个字节。这是因为必须为字符串末尾的空值保留一个额外的字节。
In addition to what others have said, keep in mind that a string with a length of three characters requires four bytes when converted to a c_str. This is because an extra byte has to be reserved for the null at the end of the string.
C++ 中的数组必须知道其大小,并在编译时提供初始化程序。 c_str() 返回的值仅在运行时已知。如果 e1 是一个 std::string(它可能应该是这样),就不会有问题。如果它必须是 char[],则使用 strcpy 来填充它。
这假设字符串 myvector[1] 最多包含两个字符。
Arrays in C++ must know their size, and be provided with initialisers, at compile-time. The value returned by c_str() is only known at run-time. If e1 were a std::string, as it probably should be, there would be no problem. If it must be a char[], then use strcpy to populate it.
This assumes that the string myvector[1] contains at most two characters.
只需创建该字符串的副本即可。然后,如果您需要将其作为 char* 访问,就这样做吧。
如果不需要修改字符串,请将其设为常量。如果需要,可以在 'el' 上使用 c_str() 。
或者,只需从向量中直接访问它:
如果可能适合您的情况。
Just create a copy of the string. Then, if you ever need to access it as a char*, just do so.
Make the string const if you don't need to modify it. Use c_str() on 'el' instead if you want.
Or, just access it right from the vector with:
if possible for your situation.