const用於指標

來源:互聯網
上載者:User
1)const int *pp是一個指向整型常量的指標,可以修改指標的值,但不能修改指標所指向的值#include <stdio.h>int main(){    int b = 5;    int c = 3;    const int *p = &b;    printf("*p is %d\n",*p);    *p = 6;//錯誤,向唯讀位置 *p賦值    p = &c;//可以修改指標的值    printf("*p is %d\n",*p);    return 0;}
2)int const * p和1)中的用法相同,p是一個指向整型常量的指標

3)int * const p;p是一個常指標,指標p是常量,它的值無法修改,但p指向的整型的值可以修改#include <stdio.h>int main(){    int b = 5;    int c = 3;    int * const p = &b;    printf("*p is %d\n",*p);    *p = 6;//正確    p = &c;//錯誤,向唯讀變數p賦值    printf("*p is %d\n",*p);    return 0;}

4)const int * const p無論指標本身還是它所指向的值都是常量,不能修改#include <stdio.h>int main(){    int b = 5;    int c = 3;    const int * const p = &b;    printf("*p is %d\n",*p);    *p = 6;//錯誤,向唯讀位置 *p賦值    p = &c;//錯誤,向唯讀變數p賦值    printf("*p is %d\n",*p);    return 0;}

簡單的辨別這幾種用法的判斷方法

  沿著*號一條線,如果const位於*左側,那麼const就是用來修飾指標所指向的變數,即指標指向常量;

  如果const位於*右側,那麼const就是用來修飾指標本身,即指標本身是常量。

  這樣是不是很好的就知道了const到底修飾誰了呢?大家也可以試試哈 ^_^

聯繫我們

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