结构体的深拷贝和浅拷贝问题

 

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct Teacher
{
	char name[64];
	int age;
	char *pname2;
};
void copyTeacher(Teacher *to, Teacher *from)
{
   *to = *from;
	//memcpy(to, from, sizeof(Teacher));
	to->pname2 = (char *)malloc(100);
	strcpy(to->pname2, from->pname2);

}
int main()
{
	Teacher t1;
	Teacher t2;
	strcpy(t1.name, "name1");
	t1.pname2 = (char *)malloc(100);
   strcpy(t1.pname2, "ssssssss");

    copyTeacher(&t2, &t1);
   if (t1.pname2 != NULL)
   {
	   free(t1.pname2);
	   t1.pname2 = NULL;
   }
   if (t2.pname2 != NULL)
   {
	   free(t2.pname2);
	   t2.pname2 = NULL;
   }
return 0;
}

 

#define  _CRT_SECURE_NO_WARNINGS 
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define NAME_LEN  64

struct teacher
{
	int id;
	char *name;
};


//如果结构体中有指针 在堆上开辟的空间
//以下这个拷贝函数, 就是浅拷贝
//结构体可以通过变量直接赋值, 但不要使用这种方法, 
//要给结构体中的成员 一个一个拷贝
void copy_teacher(struct teacher *to, struct teacher *from)
{
	*to = *from;
}

void copy_teacher_deep(struct teacher *to, struct teacher *from)
{
	to->name = (char*)malloc(NAME_LEN);
	memset(to->name, 0, NAME_LEN);
	strcpy(to->name, from->name);

	to->id = from->id;
}


void print_teacher(struct teacher *tp)
{
	printf("id : %d, name : %s\n", tp->id, tp->name);
}

int main(void)
{
	struct teacher tp1 = {0}; //在栈上开辟的一个teacher结构体
	struct teacher tp2 = {0};

	tp1.id = 1;
	tp1.name = (char*)malloc(NAME_LEN);
	memset(tp1.name, 0, NAME_LEN);
	strcpy(tp1.name, "zhang3");

	//copy_teacher(&tp2, &tp1);
	copy_teacher_deep(&tp2, &tp1);

	print_teacher(&tp1);
	print_teacher(&tp2);

	if (tp1.name != NULL) {
		free(tp1.name);
		tp1.name = NULL;
	}

	if (tp2.name != NULL) {
		free(tp2.name);
		tp2.name = NULL;
	}



	return 0;
}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值