指向const的指针和const指针

指向常量的指针 和 常量指针

#include <iostream>
#include <string>
using namespace std;
int main()
{
    typedef string *pstring;
    string s("abc"),s2("ABC");
    const pstring cstr = &s;    //相当于声明string *const cstr; //常量指针
    //cstr=&s2;   //error: assignment of read-only variable 'cstr'|
    cout<<*cstr<<endl;
//--------------------------------------------------
    //常量指针,不能再指向其它变量
    double d=3.14,d2=4.14;
    double * const pd=&d;
    pd=&d2;     //error: assignment of read-only variable 'pd'|
    cout<<*pd<<endl;
//--------------------------------------------------

    //指向const对象的指针 ,不能通过指针修改其所指空间的值
    double d=3.14;
    const double *pd=&d;    //double const *pd=&d;
    *pd=4.14;   //编绎时: error: assignment of read-only location '* pd'|
    cout<<*pd<<endl;
//--------------------------------------------------

    int arr[][1]={ 1,2,3,4,5,6};    //6行1列
    //int **p=(int **)arr;
    int (*w)[3]=(int (*)[3])arr;    //转化为 2行3列
    cout<<w[1][1]<<endl;

    return 0;
}


在下面的声明中,圆括号是必不可少的:
int *ip[4];     // array of pointers to int
int (*ip)[4];    // pointer to an array of 4ints

原文地址:https://www.cnblogs.com/wucg/p/1859217.html