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
# 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;
st2.str = ( char *) malloc ( sizeof ( char ) * 20);
strcpy (st2.str, st1.str);
st1.str[0] = 'X' ;
st1.str[1] = 'Y' ;
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