指標-傳遞動態記憶體

來源:互聯網
上載者:User
/*一道經典的面試題,有時候會搞錯。貼出來,希望大家都注意。*/char * GetMemory(char *p, int num){p = (char *)malloc(sizeof(char) * num);return p;};int main(){char *str = NULL;str = GetMemory(str, 100);strcpy(str, "hello");cout << str << endl;return 0;}/*請問以上程式的輸出是什嗎?*/void GetMemory(char *p, int num){p = (char *)malloc(sizeof(char) * num);};int main(){char *str = NULL;    GetMemory(str, 100);strcpy(str, "hello");cout << str << endl;return 0;}/*沒有輸出值。而且,每執行一次GetMemory就會申請一塊記憶體,但申請的記憶體卻不能有效釋放,結果是記憶體一直被獨佔,最終造成記憶體泄露。*//*如果一定要用指標參數去申請記憶體,那麼應該採用指向指標的指標,傳str的地址給函數GetMemory。代碼如下:*/void GetMemory(char **p, int num){*p = (char *)malloc(sizeof(char) * num); /*  *   str和 *p 表示同一個記憶體單元  *返回申請到的記憶體的首地址addr給str變數;                                          *此時str這個字元指標僅僅作為一個記憶體單元,      *其內容即為addr。  */};int main(){char *str = NULL;    GetMemory(&str, 100);                   /* *將 str這個字元指標的地址作為實參傳遞給指標的指標p。                                         *p和&str內容相同,但不是同一個記憶體單元。 */strcpy(str, "hello");cout << str << endl;return 0;}/*運行之後,可以看到預期的hello字串。*//*另外可以用函數傳回值來傳遞動態記憶體。代碼如下:*/char * GetMemory(char *p, int num){p = (char *)malloc(sizeof(char) * num);return p;};int main(){char *str = NULL;    str = GetMemory(str, 100);strcpy(str, "hello");cout << str << endl;return 0;}/*運行之後,可以看到預期的hello字串。*/

 又積累了一點,加油!

期待早點把自己賣出去!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.