深拷贝和浅拷贝多出现于结构体中的指针中的。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Teacher{
char name[64];
int age;
char *pname;
}Teacher;
//编译器的=号操作,只会把变量的值 拷贝过去 从from拷贝到to
//但不会执行内存空间的拷贝
//浅拷贝是结构体中套指针
//那如果想执行深拷贝
void copyTeacher(Teacher *to,Teacher *from){
*to = *from;
to->pname = (char *)malloc(100);
strcpy(to->pname,from->pname); //深拷贝
//memcpy(to,from,sizeof(Teacher));
}
int main(){
Teacher t1;
Teacher t2;
strcpy(t1.name,"name1");
t1.pname = (char*)malloc(100);
strcpy(t1.pname,"name2");
//t1 copyto t2
copyTeacher(&t2,&t1);
if(t1.pname!= NULL){
free(t1.pname);
t1.pname = NULL;
}
if(t2.pname!=NULL){
free(t2.pname);
t2.pname = NULL;
}
return 0;
}