Shallow copy and deep copy (structure) in C language

Shallow copy 

 

#include<stdio.h>
#include<string.h>

struct Person{

	char name[64];
	int age;
};
void test01()
{
	struct Person p1 = {"Tom",18};

	struct Person p2 = {"Jerry",20};

	p1 = p2;   //浅拷贝,逐字节拷贝

	printf("p1的姓名:%s  年龄: %d\n",p1.name,p1.age);
	printf("p2的姓名:%s  年龄: %d\n",p2.name,p2.age);

}
int main()
{
	test01();
	return 0;
}

Deep copy

The member char name[64] -> char* name in the structure

 

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct Person{

	char* name;
	int age;
};
void test01()
{
	struct Person p1;
	struct Person p2;

	p1.age = 18;
	p1.name = (char*)malloc(sizeof(char)*64);
	strcpy(p1.name,"Tom");

	
	p2.age = 20;
	p2.name = (char*)malloc(sizeof(char)*128);
	strcpy(p2.name,"Jerry");
	p1 = p2;   

	printf("p1的姓名:%s  年龄: %d\n",p1.name,p1.age);
	printf("p2的姓名:%s  年龄: %d\n",p2.name,p2.age);

}
int main()
{
	test01();
	return 0;
}

The above program can print out the corresponding information without error. But if we manually and explicitly release the memory, there will be problems. as follows

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct Person{

	char* name;
	int age;
};
void test01()
{
	struct Person p1;
	struct Person p2;

	p1.age = 18;
	p1.name = (char*)malloc(sizeof(char)*64);
	strcpy(p1.name,"Tom");

	
	p2.age = 20;
	p2.name = (char*)malloc(sizeof(char)*128);
	strcpy(p2.name,"Jerry");
	p1 = p2;   

	printf("p1的姓名:%s  年龄: %d\n",p1.name,p1.age);
	printf("p2的姓名:%s  年龄: %d\n",p2.name,p2.age);

	if(p1.name != NULL)
	{
		free(p1.name);
		p1.name = NULL;
	}
	if(p2.name != NULL)
	{
		free(p2.name);
		p2.name = NULL;
	}
}
int main()
{
	test01();
	return 0;
}

           

Solution: Do the copy operation manually

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct Person{

	char* name;
	int age;
};
void test01()
{
	struct Person p1;
	struct Person p2;

	p1.age = 18;
	p1.name = (char*)malloc(sizeof(char)*64);
	strcpy(p1.name,"Tom");

	
	p2.age = 20;
	p2.name = (char*)malloc(sizeof(char)*128);
	strcpy(p2.name,"Jerry");
	//p1 = p2;   
	//自己提供复制操作   深拷贝
	//先释放原有内容
	if(p1.name != NULL)
	{
		free(p1.name);
		p1.name = NULL;
	}

	p1.name = (char*)malloc(strlen(p2.name) + 1);
	strcpy(p1.name,p2.name);
	p1.age = p2.age ;


	printf("p1的姓名:%s  年龄: %d\n",p1.name,p1.age);
	printf("p2的姓名:%s  年龄: %d\n",p2.name,p2.age);

	if(p1.name != NULL)
	{
		free(p1.name);
		p1.name = NULL;
	}
	if(p2.name != NULL)
	{
		free(p2.name);
		p2.name = NULL;
	}
}
int main()
{
	test01();
	return 0;
}

 

                                                                                                                Adopt VS2010 environment

 

 

 

Guess you like

Origin blog.csdn.net/weixin_42596333/article/details/104504243