[Solved] Deep Copy of string using new Operator over loading [closed]


Your main function should be like the following,

int main()
{
   char *str = "hello world";
   char *shallowCopy = str;
   char *deepcopy = new char[(strlen(str) + 1)];

   while (*str != '\0')
   {
     *deepcopy = *str;
      deepcopy++;
      str++;
   }
  *deepcopy = '\0';
  cout << "\n\n shallow string is :-" << shallowCopy << endl;
  cout << "\n\n deep string is :-" << deepcopy - strlen(shallowCopy) << endl;  /* here*/
}

The reason is that after the while loop, the pointers, str and deepcopy are pointed to the end of the string. Note that the line *deepcopy = '\0'; will make pointer deepcopy point to a NULL character, or, the C-string termination character.

Then you also need to remember to call delete.

5

solved Deep Copy of string using new Operator over loading [closed]