结构体的深拷贝与浅拷贝
2024-07-22 本文已影响0人
爱学习的猫叔
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
typedef struct Student {
char* name;
int age;
}Student;
void deepCopyStu(Student* from, Student* to) {
//malloc分配的内存需要包括字符串的末尾空字符 '\0',否则,strcpy 会试图写入超出分配内存的空间,从而导致未定义行为或崩溃。
to->name = malloc(strlen(from->name)+1);
strcpy(to->name,from->name);
to->age = from->age;
}
void main(){
Student stu1;
stu1.name = (char*)malloc(100);
strcpy(stu1.name,"Yaphets");
stu1.age = 20;
printf("stu1: name = %s, age = %d\n",stu1.name,stu1.age);
//浅拷贝1
Student stu2;
stu2.name = stu1.name;
stu2.age = stu1.age;
printf("%p,%p\n", &stu1, &stu2);
printf("stu2: name = %s, age = %d\n", stu2.name, stu2.age);
Student stu3;
//浅拷贝2
stu3 = stu1;
printf("%p,%p\n", &stu1, &stu3);
printf("stu3: name = %s, age = %d\n", stu3.name, stu3.age);
strcpy(stu1.name, "Teddy");
printf("stu1: name = %p\n", stu1.name);
printf("stu2: name = %p\n", stu2.name);
printf("After modifying stu1.name:\n");
printf("stu1: name = %s, age = %d\n", stu1.name, stu1.age);
printf("stu2: name = %s, age = %d\n", stu2.name, stu2.age);
printf("stu3: name = %s, age = %d\n", stu3.name, stu3.age);
Student stu4;
//深拷贝
deepCopyStu(&stu1, &stu4);
strcpy(stu1.name, "Bob");
printf("After modifying stu1.name:\n");
printf("%p,%p,%p,%p\n", &stu1, &stu2, &stu3, &stu4);
printf("stu1: name = %p\n", stu1.name);
printf("stu4: name = %p\n", stu4.name);
printf("stu1: name = %s, age = %d\n", stu1.name, stu1.age);
printf("stu2: name = %s, age = %d\n", stu2.name, stu2.age);
printf("stu3: name = %s, age = %d\n", stu3.name, stu3.age);
printf("stu4: name = %s, age = %d\n", stu4.name, stu4.age);
free(stu1.name);
free(stu4.name);
getchar();
}
运行结果
stu1: name = Yaphets, age = 20
0075FC3C,0075FC2C
stu2: name = Yaphets, age = 20
0075FC3C,0075FC1C
stu3: name = Yaphets, age = 20
stu1: name = 00C1BB80
stu2: name = 00C1BB80
After modifying stu1.name://浅拷贝改变stu1的string内容,stu2和stu3的string内容会跟着改
stu1: name = Teddy, age = 20
stu2: name = Teddy, age = 20
stu3: name = Teddy, age = 20
After modifying stu1.name:
0075FC3C,0075FC2C,0075FC1C,0075FC0C
stu1: name = 00C1BB80
stu4: name = 00C1BA20//深拷贝时重新分配的内存
stu1: name = Bob, age = 20
stu2: name = Bob, age = 20
stu3: name = Bob, age = 20
stu4: name = Teddy, age = 20//修改stu1的string内容后不影响stu4的string内容