C++ equivalent for memset on char*

Para picture Para · Jan 24, 2010 · Viewed 16.4k times · Source

I have this code

  char * oldname = new char[strlen(name) + 1];

  memcpy(oldname,name,strlen(name) + 1);

  name = new char[strlen(oldname) + strlen(r.name) + 1];
  memset(name, '\0', strlen(name));

  strcat(name,oldname);
  strcat(name," ");
  strcat(name,r.name);

I understand that it is a no no to use memcpy and memset but I haven't understood exactly how to use this in C++, preferably without std.

Does anyone know? Thank you.

Answer

jamesdlin picture jamesdlin · Jan 24, 2010

In general, there's std::fill. http://www.cplusplus.com/reference/algorithm/fill/

Or in this particular instance, you should consider using std::vector<char>.

(Note that memset can still be used in C++ if you use #include <cstring>, although it's less idiomatic in C++.)