一、浅拷贝:
对于浅拷贝我的理解是:一个空间去拷贝另外一个空间的内容,但是它是整体拷贝里面的内容,在计算机中它只会保存一份,所以当你两片空间同时释放时,它会报你两次对同一片空间释放错误:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct student
{
int num;
char *name;
}stu;
int main(int argc, char *argv[])
{
stu s1,s2;
s1.num = 10;
s1.name = (char*)malloc(10);//申请堆空间malloc需要强转类型
s2.name = (char*)malloc(10);
strcpy(s1.name,"zhangsan");
//memcpy(&s1,&s2,sizeof(stu));//整体拷贝:方法二
s2 = s1;//方法一
printf("s1:%d %s\n",s1.num,s1.name);
printf("s2:%d %s\n",s2.num,s2.name);
printf("&s1:%p %p\n",&s1.num,&s1.name);
printf("&s2:%p %p\n",&s2.num,&s2.name);
if(s1.name != NULL)
{
free(s1.name);
}
if(s2.name != NULL)
{
free(s2.name);//会报重复释放堆错误
}
return 0;
}
二、深拷贝:
对于深拷贝我的理解是:就跟考试时你去抄袭别人试卷一样,你需要一个一个的去抄,但是这张试卷始终是你的,所以两张试卷是两个地址;两次释放也不会报错。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct student
{
int num;
char *name;
}stu;
int main(int argc, char *argv[])
{
stu s1,s2;
s1.num = 10;
s1.name = (char*)malloc(20);
s2.name = (char*)malloc(20);
strcpy(s1.name,"zhangsan");
//都需要单独拷贝
memcpy(s2.name,s1.name,strlen(s1.name)+1);//方法一
s2.num = s1.num;//num 也需要单独拷贝
//strcpy(s2.name,s1.name);//方法二
printf("s1:%d %s\n",s1.num,s1.name);
printf("s2:%d %s\n",s2.num,s2.name);
printf("&s1:%p %p\n",&s1.num,&s1.name);
printf("&s2:%p %p\n",&s2.num,&s2.name);
if(s1.name != NULL)
{
free(s1.name);
}
if(s2.name != NULL)
{
free(s2.name);//不会报错
}
return 0;
}