Reputation: 63
I have
std::ostringstream out;
out << name << len << data;
std::string const value = out.str();
I want to copy this const value to a char*
char* buff;
size_t length = strlen(value);
buff = new char[(strlen(value))+ 1];
memcpy(nm, value , length + 1);
but it is still giving me error? Can you please tell me what I am doing wrong? Thank you.
Upvotes: 0
Views: 2598
Reputation: 88
Why are you using memcpy anyway? There is strcpy for the purpose of copying strings:
char *c = new char[value.length() + 1];
strcpy(c, value.c_str());
Upvotes: 0
Reputation: 361772
Use value.size()
instead of strlen(value)
.
char* buff;
size_t length = value.size();
buff = new char[length+1];
memcpy(buff, value.c_str() , length + 1);
//^^^^ ^^^^^^^^^^^ also note this
Or you can copy in this as well:
std::string copy = value;
const char * buff = copy.c_str();
But note that buff
will exist as long as the variable copy
exists. In other words, the lifetime of buff
is tied with the lifetime of the variable copy
, and you don't need to write delete buff
in this case.
Upvotes: 4