常量指標 和 指標常量

來源:互聯網
上載者:User

在C++的學習中,有人經常搞不清楚“常量指標”和“指標常量”這兩個概念。其實簡單一點講,“常量指標”所指向的地址上的資料是常量,而“指標常量”所指向的地址是常量,地址上面的資料是可以變化的。

     下面看及格簡單的例子,可以說明他們的區別:
            第一個

 1 void main(){
 2     char *str1={"Hello"};
 3     char *str2={"Hello World"};
 4     char * const ptr1 =str1 ;
 5     //指標常量--指標本身是常量,指向的地址不可以變化,但是指向的地址所對應的內容可以變化
 6 
 7     ptr1 =str2; //錯誤 因為這是一個常量指標,改變指向的地址了
 8 
 9     printf("%s \n",*ptr1);
10     }
11 
12 
13 // 編譯錯誤    error C3892: 'ptr1' : you cannot assign to a variable that is const    
14 

第二個

 1 void main(){
 2     char *str1={"Hello"};
 3     char *str2={"Hello World"};
 4     char * const ptr1 =str1 ;
 5     //指標常量--指標本身是常量,指向的地址不可以變化,但是指向的地址所對應的內容可以變化
 6 
 7     *ptr1 ='A';// 正確 因為指向的地址的內容是可以變化的
 8 
 9     printf("%c \n",*ptr1);
10     }
11 
12 //輸出  A
13 

第三個

 1 void main(){
 2     char *str1={"Hello"};
 3     char *str2={"Hello World"};
 4     const char *ptr1 = str1;
 5     //常量指標--指向字串常量,所指向的字串內容不能變,但是指向的地址可以變化
 6     
 7     ptr1=str2;// 正確 因為指向的地址是可以變化的
 8 
 9     printf("%s \n",ptr1);
10     }
11 
12 //輸出 Hello World

第四個

 1 void main(){
 2     char *str1={"Hello"};
 3     char *str2={"Hello World"};
 4     const char *ptr1 = str2;
 5     //常量指標--指向字串常量,所指向的字串內容不能變,但是指向的地址可以變化
 6     
 7     ptr1='A';// 錯誤 因為指向的地址是內容是不可以變化的
 8 
 9     printf("%c \n",ptr1);
10     }
11 
12 
13 //編譯錯誤    error C2440: '=' : cannot convert from 'char' to 'const char *'
14 

相信從上面四個簡單的例子可以看出他們不一樣的地方把,在這裡要請大家注意一下的地方是:

指標常量的申明:const 放在* 和指標名之間 Type * const pointer ;

常量指標的申明:const放在類型說明符之前 const Type *pointer ;

聯繫我們

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