Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Deep Copy of Struct Member Arrays in C
In C, when you assign one structure variable to another, a shallow copy is typically performed. However, there is an important exception: if a structure member is an array, the compiler automatically performs a deep copy of that array. This means the array contents are copied element by element, creating independent copies in memory.
Syntax
struct_type destination = source; // Assignment copies all members
Example: Deep Copy of Array Members
The following example demonstrates how array members within structures are deep copied automatically −
#include <stdio.h>
#include <string.h>
typedef struct student {
int roll_num;
char name[128];
} student_t;
void print_struct(student_t *s) {
printf("Roll num: %d, name: %s<br>", s->roll_num, s->name);
}
int main() {
student_t s1, s2;
s1.roll_num = 1;
strcpy(s1.name, "tom");
s2 = s1; // Deep copy of array member occurs here
// Modify s2's array - s1 remains unaffected due to deep copy
s2.name[0] = 'T';
s2.name[1] = 'O';
s2.name[2] = 'M';
printf("After modifying s2:<br>");
print_struct(&s1);
print_struct(&s2);
return 0;
}
After modifying s2: Roll num: 1, name: tom Roll num: 1, name: TOM
How It Works
When s2 = s1 is executed:
- The
roll_numinteger is copied by value (shallow copy) - The
namearray is copied element by element (deep copy) - Both structures have independent copies of the array data
- Modifying
s2.namedoes not affects1.name
Key Points
- Array members in structures are automatically deep copied during assignment
- This behavior is built into the C language specification
- No manual memory management is required for static arrays within structures
- This does not apply to pointer members − they would still be shallow copied
Conclusion
C automatically performs deep copy for array members within structures during assignment. This ensures data independence between structure instances, making it safe to modify array contents without affecting the original structure.
Advertisements
