将const复制为char*

Copy const to char*

本文关键字:char 复制 const      更新时间:2023-10-16

我有

       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());