char arr[] 和 char *arr區別

來源:互聯網
上載者:User
char arr[] = "hello world";//arr為數組的名稱,數組中的內容在棧中,離開數組所在的範圍,所佔用的空間就被釋放。char *arr = "hello world";//arr為指標,arr佔用的記憶體為棧中的記憶體,但其指向的記憶體在靜態儲存區,靜態儲存區的空間在程式結束的時候,才被釋放。下面是一個小的程式,GetString01() 和GetString02()函數。GetString01()函數,當返回數組的名稱時,數組的內容就被釋放了。GetString02()函數,當返回指標時,指標所指的內容沒有被釋放。所以,GetString02()函數可以正確的返回內容,GetString01()返回的是亂碼。
#include<iostream>#include<string>using namespace std;char * GetString01(){char arr[] = "hello world";return arr;}char * GetString02(){char *arr = "hello world";return arr;}int main(){char *p = GetString01();cout<<p<<endl;char *q = GetString02();cout<<q<<endl;system("pause");    return 0;}
結果的截圖如下:

聯繫我們

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