我如何转换const char*
为char[256]
?
const char *s = std::string("x").c_str();
char c[256] = /* ??? */
不能用字符指针初始化数组。但是你可以复制字符串。例如:
const char *s = get_the_string();
char c[256]{};
auto n = std::strlen(s);
if (std::size(c) <= n)
throw std::runtime_error(
"The buffer is too small. Contact your local C++ maintainer");
std::memcpy(c, s, n);
使用恒定大小的数组的明显问题是您需要考虑如何处理输入字符串不适合的情况。在这里,我使用了一个异常,但是如果这不是您的选择,您可以使用您选择的错误处理。
您不能从 a 复制const char *s = std::string("x").c_str();
,因为指针悬空,并且尝试访问指向的数据将具有未定义的行为。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句