0 votes
in C Plus Plus by
What are the differences Deep Copy and Shallow Copy with examples?

1 Answer

0 votes
by

In the following C program, struct variable st1 contains pointer to dynamically allocated memory. When we assign st1 to st2, str pointer of st2 also start pointing to same memory location. This kind of copying is called Shallow Copy

// C program to demonstrate shallow copy

# include <stdio.h>

# include <string.h>

# include <stdlib.h>

struct test

{

char *str;

};

int main()

{

struct test st1, st2;

st1.str = (char *)malloc(sizeof(char) * 20);

strcpy(st1.str, "Madanswer");

st2 = st1;

st1.str[0] = 'X';

st1.str[1] = 'Y';

/* Since copy was shallow, both strings are same */

printf("st1's str = %s\n", st1.str); 

printf("st2's str = %s\n", st2.str);

return 0;

}

Output: 
st1's str = XYMadanswer
st2's str = XYMadanswer

 

To do Deep Copy, we allocate new memory for dynamically allocated members and explicitly copy them.

C

// C program to demonstrate deep copy
# include <stdio.h>
# include <string.h>
# include <stdlib.h>
 
struct test
{
  char *str;
};
 
int main()
{
  struct test st1, st2;
  st1.str = (char *)malloc(sizeof(char) * 20);
 
  strcpy(st1.str, "Madanswer");
 
  st2 = st1;
 
  // We add extra statements to do deep copy
  st2.str = (char *)malloc(sizeof(char) * 20);
  strcpy(st2.str, st1.str);
 
  st1.str[0] = 'X';
  st1.str[1] = 'Y';
 
  /* Since copy was deep, both strings are different */
  printf("st1's str = %s\n", st1.str);
  printf("st2's str = %s\n", st2.str);
 
  return 0;
}
Output: 
st1's str = XYMadanswer
st2's str = Madanswer

Related questions

+2 votes
0 votes
asked Jan 12 in C Plus Plus by GeorgeBell
0 votes
asked Jan 12 in C Plus Plus by GeorgeBell
...