In C programming, a shallow copy and a deep copy are two different methods of copying the contents of a variable from one location to another.
A shallow copy only copies the top-level values of a variable, while a deep copy copies all of the values, including any sub-objects or references.
Let’s take an example of a structure in C to illustrate the difference between a shallow copy and a deep copy.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct person {
char *name;
int age;
} Person;
int main() {
// create a person object
Person *person1 = (Person *) malloc(sizeof(Person));
person1->name = "John";
person1->age = 25;
// shallow copy
Person *person2 = person1;
// deep copy
Person *person3 = (Person *) malloc(sizeof(Person));
person3->name = (char *) malloc(strlen(person1->name) + 1);
strcpy(person3->name, person1->name);
person3->age = person1->age;
// modify the original object
person1->name = "Jane";
person1->age = 30;
// print the contents of each object
printf("person1: %s (%d)n", person1->name, person1->age);
printf("person2: %s (%d)n", person2->name, person2->age);
printf("person3: %s (%d)n", person3->name, person3->age);
return 0;
}
In this example, we define a Person structure that contains a name and an age field. We then create a new Person object person1 with the name "John" and age 25.
Next, we create a shallow copy of person1 by assigning its pointer to person2. This means that person2 points to the same memory location as person1.
We also create a deep copy of person1 by allocating new memory for the name field and copying the string from person1. This ensures that person3 has its own copy of the name field that is not affected by changes to person1.
Finally, we modify the name and age fields of person1. Since person2 points to the same memory location as person1, its values also change. However, since person3 has its own copy of the name field, its value does not change.
When we print out the contents of each object, we can see the difference between the shallow and deep copies. person1 and person2 have the same name "Jane" and age 30, while person3 still has the original name "John" and age 25.
In general, a shallow copy is faster and more memory-efficient, but can lead to unintended consequences if the original object is modified. A deep copy is safer but may require more memory and time to create. The choice between a shallow copy and a deep copy depends on the specific requirements of the program.