[C++] C++指標的那些事 — 常量,變數,指標及指標相關的三個數值

來源:互聯網
上載者:User

常量: 只有資料, 雖然也佔用儲存空間, 但在編譯後的代碼中只引用資料,沒有地址的概念.如:

const string hi = "hello";

const int days = 31;

 

變數: 儲存在記憶體裡的資料(右值), 修改時需要引用地址(左值). 如:

int  num = 12;

float d = 354.333F;

bool b = true;

 

而指標則要關注3個數值: 儲存指標變數的記憶體位址, 指標指向的記憶體位址, 指標指向的值.

若定義一個指標變數:  

int num = 8;

 int p*= #

則這三個數值則分別表示為: &p, p, *p.

如下樣本:

 int main() {int *p=NULL;cout<<"初始化後未賦值:"<<endl;cout<<"指標變數地址(&p) = "<<&p<<endl;cout<<"指標指向的地址(p) = "<<p<<endl;if (p!=NULL)cout<<"指標指向地址儲存的值(*p) = "<<*p<<endl;elsecout<<"null 指標, 不能取值."<<endl;p= new int(1024);cout<<"賦值後:"<<endl;cout<<"指標變數地址(&p) = "<<&p<<endl;cout<<"指標指向的地址(p) = "<<p<<endl;if (p!=NULL)cout<<"指標指向地址儲存的值(*p) = "<<*p<<endl;elsecout<<"null 指標, 不能取值."<<endl;delete p;p = NULL;cout<<"釋放後:"<<endl;cout<<"指標變數地址(&p) = "<<&p<<endl;cout<<"指標指向的地址(p) = "<<p<<endl;if (p!=NULL)cout<<"指標指向地址儲存的值(*p) = "<<*p<<endl;elsecout<<"null 指標, 不能取值."<<endl;               return 0;}

 弄明白這三者的關係與區別, 就可以很清楚的理解指標了.

 特別提示: 定義指標時最好賦值先NULL, 而釋放指標時(delete) 則最好也賦值 NULL, 這樣就可以避免一些錯誤的指標動作.

相關文章

聯繫我們

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