Deep vs shallow copies of nested structs
What you'll learn: You will understand why simple assignment fails when structures contain pointers to other data and how to manually perform a deep copy.
The problem with the equals sign
In C, you can copy one struct to another using the = operator. If your struct contains simple values like integers or floats, this works perfectly. However, things get tricky when your struct is "nested" with pointers to other memory locations (like strings or dynamic arrays).
Imagine you have a Person struct that contains a pointer to a Job struct. If you perform a shallow copy (Person2 = Person1), C simply copies the memory address stored in the pointer. Now, both people are pointing to the exact same Job object in memory. If you change the job title for Person 1, it magically changes for Person 2 as well. They aren't just working the same job; they are sharing the same physical desk!
Shallow vs. Deep
- Shallow Copy: Only the top-level struct members are copied. Pointers inside the struct still point to the original addresses.
- Deep Copy: You manually allocate new memory for the nested components and copy the actual data over. This ensures the new struct has its own independent version of the nested data.
Code Example: Performing a Deep Copy
To perform a deep copy, you must avoid a simple assignment and instead "build" the new struct piece by piece.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Job {
char title[20];
};
struct Person {
int id;
struct Job *work; // Pointer to a nested struct
};
int main() {
// 1. Setup original
struct Person p1;
p1.id = 1;
p1.work = malloc(sizeof(struct Job));
strcpy(p1.work->title, "Engineer");
// 2. Perform a DEEP copy
struct Person p2;
p2.id = p1.id; // Simple values can be copied directly
// Allocate NEW memory for the nested struct
p2.work = malloc(sizeof(struct Job));
// Copy the actual data, not just the address
strcpy(p2.work->title, p1.work->title);
// Now, changing p1 won't affect p2
strcpy(p1.work->title, "Manager");
printf("P1: %s, P2: %s\n", p1.work->title, p2.work->title);
free(p1.work);
free(p2.work);
return 0;
}
Key takeaway
A shallow copy only copies memory addresses, causing two structs to share nested data; a deep copy allocates new memory to ensure the copy is truly independent.