intmain(){intx{5};int*ptr{&x};// ptr is a normal (non-const) pointerinty{6};ptr=&y;// we can point at another value*ptr=7;// we can change the value at the address being heldreturn0;}
intmain(){intx{5};// non-constconstint*ptr{&x};// ptr points to a "const int"*ptr=6;// not allowed: ptr points to a "const int" so we can't change the value through ptrx=6;// allowed: the value is still non-const when accessed through non-const identifier xreturn0;}
常量指针
指针自身也可以是常量。一个常量指针的地址,在初始化之后是不能够被修改的。
声明一个常量指针,只需要在指针声明的星号后添加const 关键字:
1234567
intmain(){intx{5};int*constptr{&x};// const after the asterisk means this is a const pointerreturn0;}
在上面的例子中,ptr 是一个指向(非 const) int 值的 const 指针。
就像普通的const变量一样,const指针必须在定义时初始化,并且这个值不能通过赋值来改变:
1 2 3 4 5 6 7 8 910
intmain(){intx{5};inty{6};int*constptr{&x};// okay: the const pointer is initialized to the address of xptr=&y;// error: once initialized, a const pointer can not be changed.return0;}
不过,该指针所指的对象并不是一个常量,所以仍旧可以通过对指针解引用然后修改该变量的值:
123456789
intmain(){intx{5};int*constptr{&x};// ptr will always point to x*ptr=6;// okay: the value being pointed to is non-constreturn0;}