c++淺複製和深複製

來源:互聯網
上載者:User

標籤:分配   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++淺複製和深複製

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.