Deep Copy of Struct Member Arrays in C

CServer Side ProgrammingProgramming

Structure allows us to create user defined datatype. Structure member can be primitive datatype or it can be an array of statically allocated memory. When we assign one structure variable to another then shallow copy is performed. However, there is an exception, if structure member is an array then compiler automatically performs deep copy. Let us see this with example −

Example

 Live Demo

#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\n", s->roll_num, s->name);
}
int main() {
   student_t s1, s2;
   s1.roll_num = 1;
   strcpy(s1.name, "tom");
   s2 = s1;
   // Contents of s1 are not affected as deep copy is performed on an array
   s2.name[0] = 'T';
   s2.name[1] = 'O';
   s2.name[2] = 'M';
   print_struct(&s1);
   print_struct(&s2);
   return 0;
}

Output

When you compile and execute above code it will generate following output −

Roll num: 1, name: tom
Roll num: 1, name: TOM
raja
Published on 26-Sep-2019 13:43:18
Advertisements