c++ - How to perform a deep copy of a char *? -
i'm little confused on how perform deep copy of char *. have:
appointment(appointment& a) { subject = new char; *subject = *(a.subject); } appointment(appointment& b) { location = new char; *location = *(b.location); } char *subject; char *location; i'm trying perform deep copy of char pointers subject , location. work? if not, advice on how go doing this?
since using c++ should using std::string string needs.
the following code wrote
appointment(appointment& a) { subject = new char; *subject = *(a.subject); } will not think do, above allocate 1 character (new char) assign first character of a.subject (*subject = *(a.subject))
in order copy string char* points must first determine string length, allocate memory hold string , copy characters.
appointment(appointment& a) { size_t len = strlen(a.subject)+1; subject = new char [len]; // allocate string , ending \0 strcpy_s(subject,len,a.subject); } an alternative way char* use std::vector<char>, depends on want string.
Comments
Post a Comment