#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct Teacher { char name[64]; int age; char *pname2; }teacher; /* 编译器的=号操作会把指针变量的值,从from copy到to 但不会把指针变量所值的内存空间给copy过去 这就是浅拷贝的概率 对于结构体中含有一级指针或二级指针 需要执行深拷贝,即显示分配内存,并且执行指针赋值操作 strcpy或者memcpy */ void copyTeacher(Teacher *to, Teacher *from) { *to = *from; to->pname2 = (char *)malloc(100); strcpy(to->pname2, from->pname2); } int main() { Teacher t1; Teacher t2; strcpy(t1.name,"name1"); t1.age = 18; t1.pname2 = (char *)malloc(100); strcpy(t1.pname2,"ssss"); copyTeacher(&t2,&t1); printf("%s %d %s",t2.name,t2.age,t2.pname2); if(t1.pname2 != NULL) { free(t1.pname2); t1.pname2 = NULL; } if(t2.pname2 != NULL) { free(t2.pname2); t2.pname2 = NULL; } return 0; }