C++ memcpy to char* from c_str

Max picture Max · Jul 11, 2013 · Viewed 16.3k times · Source

I've done a bit of basic reading and from what I've gathered .c_str() always has a null terminator.

I have a fairly simple C++ program:

int main(int argc, char** argv)
{
  std::string from = "hello";
  char to[20];
  memcpy(to, from.c_str(), strlen(from.c_str())+1);
  std::cout<< to << std::endl;
  return 0;
}

Will that memcpy ensure that I copy over a null-terminated string to my variable to (provided that my string from is shorter in length)?

Answer

ronag picture ronag · Jul 11, 2013

You should use std::string to copy strings. However, if you want to do it like that you should use strcpy instead of memcpy

int main(int argc, char** argv)
{
  std::string from = "hello";
  char to[20];
  strcpy(to, from.c_str());
  std::cout<< to << std::endl;
  return 0;
}