char* a與char a[]的區別,const char* a與char* const a的區別

來源:互聯網
上載者:User

請看具體樣本

#include<iostream>using namespace std;void main(void){// char* a 與 char a[] 的區別char* a = "abcdef";        // a為一指標,其值可以改變。現在a指向的是一常量字串cout << a << endl;a = "ghijkl";              // a現在指向另一常量字串//a[0] = 'z';              // a指向的為常量,編譯沒問題,但運行出現異常cout << a << endl;cout << sizeof(a) << endl; // 4char b[] = "abcdef";       // b為數組首地址,為一常量,其值不可改變。所指內容不是常量字串cout << b << endl;//b = "ghijkl";            // 編譯無法通過,b為常量,無法為其指定其它值b[0] = 'z';cout << b << endl;cout << sizeof(b) << endl; // 7// ------------------------------------------------------------------------------// const char* a 與 char* const a 區別char c[] = "abcd";char d[] = "efgh";const char* pC = c;//pC[0] = 'z';             // 編譯出錯,pC為指向常量的指標,做不能修改指標指向的內容cout << pC << endl;pC = d;cout << pC << endl;        // pC指向的內容不能改,但可以修改指向char e[] = "abcd";char f[] = "efgh";char* const pE = e;//pE = f;                  // pE為常量指標,不能改變其指向pE[0] = 'z';               // pE為常量指標,雖然不能改變其指向,但可以修改指向內容cout << pE << endl;}// 總結:(1) char* a這種形式:a為指標,可以改變其指向,//       其所指向的字串為常量,不能修改其指向的內容。//       (2) char a[]這種形式,a為數組名,為常量,不能再//       指向其它字串,但其指向的內容不是常量字串,//       故可以改變。//       (1) const char* a 為指向常量的指標,所指內容為常量,//       不能修改,但可以改變其指向,這種形式還與//       char const * a等價。//       (2) char* const a 為指標常量,不能改變其指向,但可//       以修改其指向的內容。//       (3) const char* const a 為指向常量的常指標,即不能//       改變其指向,也不能改變其指向的內容

聯繫我們

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