将const复制为char*
Copy const to char*
我有
std::ostringstream out;
out << name << len << data;
std::string const value = out.str();
我想把这个const值复制到char*
char* buff;
size_t length = strlen(value);
buff = new char[(strlen(value))+ 1];
memcpy(nm, value , length + 1);
但它仍然给我错误?你能告诉我我做错了什么吗?谢谢你。
用value.size()
代替strlen(value)
char* buff;
size_t length = value.size();
buff = new char[length+1];
memcpy(buff, value.c_str() , length + 1);
//^^^^ ^^^^^^^^^^^ also note this
或者你也可以在这里复制:
std::string copy = value;
const char * buff = copy.c_str();
但请注意,只要变量copy
存在,buff
就会存在。换句话说,buff
的生命周期与变量copy
的生命周期绑定在一起,在这种情况下不需要编写delete buff
。
为什么要使用memcpy呢?有一个用于复制字符串的strcpy:
char *c = new char[value.length() + 1];
strcpy(c, value.c_str());
相关文章:
- 使用strcpy将char数组的元素复制到另一个数组
- 使用动态分配将 char* 复制到另一个字符**
- 如何将 cv::Mat & Img 复制到未签名的 char* img?opencv
- 我可以使用istream_iterator将<char>一些 istream 内容复制到 std::string 中吗?
- char 和 char& 之间是否存在相对复制开销差异?
- 如何在忽略 null 的同时将数据从 char [] 复制到常量字符 *
- 如何将const char*复制到c 中的uint8_t []
- C - 从const char*复制到字符串
- 将矢量<char>复制到 2D 矢量 <string> c++
- C++将 char 复制到 char 数组(调试断言失败)时,字符串不是以 null 结尾的
- 将内存从char*复制到较大char*中的某个位置
- C++ 使用 char* 复制字符数组(无字符串库)
- 将 boost::array<char> 复制到 std::string
- 如何将char复制到char*向量中
- 将子字符串从char*复制到std::string的优雅方式
- 如何在c++中将数组char复制到字符串或int*(void*)中
- 方便地将 std::vector<unsigned char> 复制到输入流 (std::istream) 对象
- 从char*复制到char[]
- 将char复制到struct指针char
- 如何有效地将 std::vector<char> 复制到 std::string