结构允许我们创建用户定义的数据类型。结构成员可以是原始数据类型,也可以是静态分配的内存数组。当我们将一个结构变量分配给另一个变量时,将执行浅表复制。但是,有一个例外,如果结构成员是数组,则编译器会自动执行深度复制。让我们通过示例看到这一点-
#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;
}输出结果
当您编译并执行上述代码时,它将生成以下输出-
Roll num: 1, name: tom Roll num: 1, name: TOM