標籤:分配 set pac gpo window 錯誤 main 結構體 cout
#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");}
c++淺複製和深複製