关于对有一级指针,二级指针的初始化及其浅拷贝和深拷贝

时间:2022-12-25 19:52:27
#include "iostream"
using namespace std;

class test
{ 
public: 
	int	a;
	char name[64];
	char* b;
	char** c;	
};
//指针初始化
	test* create()
	{
		test *p = (test *)malloc(sizeof(test ));
		memset(p, 0, sizeof(test));

		p->b = (char*)malloc(128*sizeof(char)) ;
		memset(p->b, 0, 128*sizeof(char));

		char **pc = (char **)malloc(2*sizeof(char *));
		for (int i = 0; i < 2; i++)
		{
			pc[i] =(char *)malloc(128*sizeof(char));
			memset(pc[i] , 0, 128*sizeof(char));
		}
		p->c = pc;

		return p;
	}
//赋值
	void insert(test *pArray,int x)
	{
		char *p = pArray->b;
		pArray->a=x ;
		strcpy(pArray->name,"name[4]");
		strcpy(p,"*b");

		for (int j=0; j<2; j++)
		{
			char **p2 = pArray->c;
			strcpy(p2[j],"**p");
		}
	}
//打印
	int show(test *p)
	{
		cout<<p->a<<endl;
		cout<<p->name<<endl;
		cout<<p->b<<endl;

		for (int i = 0; i < 2; i++)
		{
			char **pc = p->c;
			cout<<pc[i]<<endl;
		}
	return 0;
	}

	void freeObj(test* p)
	{
		if (p == NULL)
		{
			return ;
		}
//释放一级指针
		char *pb = p->b;
		if (pb != NULL)
		{
			free(pb);
		}
//释放二级指针
		char **pc = p->c;
		for (int i = 0; i < 2; i++)
		{
			if (pc[i] != NULL) 
			{
				free(pc[i]);
			}			
		}
		free(pc);

		if (p != NULL)
		{
			free(p);
			p = NULL; //垃圾话语
		}
	}
void  copyPointer(test *from, test *to)
{		
		to->a=from->a ;
		strcpy(to->name,from->name);

		strcpy(to->b,from->b);

		for (int j=0; j<2; j++)
		{
			char **fromc = from->c;
			char **toc = to->c;
			strcpy(toc[j],fromc[j]);
		}	
}
//实例深拷贝
void  copyObj(test *from, test *to)
{		
		memcpy(to, from, sizeof(test)) ;
		
		to->a = from->a;
		to->b = (char*)malloc(128*sizeof(char));
		strcpy(to->b,from->b);
		strcpy(to->name ,from->name);

		to->c = (char **)malloc(2*sizeof(char *));
		char** pc = to->c;
		char** fromc = from->c;
		for (int i = 0; i < 2; i++)
		{
			pc[i] =(char *)malloc(128*sizeof(char));
			memcpy(pc[i] , fromc[i], 128*sizeof(char));
		}
}

void main()
{
//正常流程
	test *p1  = create();
	insert(p1,1);
	show(p1);
	free(p1);
//浅拷贝:去掉注释会出错。原因浅拷贝公用了同一内存地址,释放一次后,再释放会出错。‘=’默认浅拷贝
	test *p2  = create();
	test *p3 = p2;
//	free(p2->b);
//	free(p1->b);

//深拷贝,指针说明,两个对象都有独立的内存空间,互不干扰;此处因为事先初始两块内存地址。
	test *p4  = create();
	insert(p4,4);	//对p4赋值
	test *p5  = create();
	copyPointer(p4,p5);
	show(p5);

//深拷贝,实例说明
	test p6;
	test p7 ;
//对p6初始化
	p6.a = 6;
	strcpy(p6.name ,"p6");
	p6.b = (char*)malloc(128*sizeof(char));
	strcpy(p6.b ,"*p6");
	char **pc = (char **)malloc(2*sizeof(char *));
	for (int i = 0; i < 2; i++)
	{
		pc[i] =(char *)malloc(128*sizeof(char));
		strcpy(pc[i] ,"**p6");
	}
	p6.c = pc;
	copyObj(&p6,&p7);
	free(p6.b);
	free(p7.b);

}