#include <iostream> #include <string> #include <windows.h> using namespace std; //定义结构体类型 typedef struct person { char name[10];//12 char *a_name;//4 } p; //创建结构体实例 p * setPersons() { p *c = (p*)malloc(sizeof(p)); cout << "name:" << endl; cin >> c->name; cout << "a_name:" << endl; char *nmm = (char *)malloc(10); cin >> nmm; c->a_name = nmm; return c; } //释放内存 void freeZoom(p* a) { //释放内部指针 if (a->a_name != NULL) { free(a->a_name); a->a_name = NULL; } if (a != NULL) { free(a); a = NULL;//这句是废话 } } void main() { //结构体内部有指针的话,要重新操作内部指针的内容,不然复制的指针会内存共享,多次释放会发生错误。 //cout << sizeof(p) << endl;//16 p* p1 = setPersons(); p* p2 = (p*)malloc(sizeof(p));//分配内存 //memcpy(p2, p1, sizeof(p1));//浅复制 *p2 = *p1;//赋值操作浅复制 cout << "a_name:" << endl; char *nmm = (char *)malloc(10);//分配内存深复制 cin >> nmm; p2->a_name = nmm; //打印 cout << p1->name << endl; cout << p1->a_name << endl; cout << p2->name << endl; cout << p2->a_name << endl; //释放内存 freeZoom(p1); p1 = NULL; freeZoom(p2); p2 = NULL; system("pause"); }