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 −


 Live Demo

#include <stdio.h>
#include <string.h>
typedef struct student {
   int roll_num;
   char name[128];
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(, "tom");
   s2 = s1;
   // Contents of s1 are not affected as deep copy is performed on an array[0] = 'T';[1] = 'O';[2] = 'M';
   return 0;


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

Roll num: 1, name: tom
Roll num: 1, name: TOM
Updated on 26-Sep-2019 13:44:41