zoukankan      html  css  js  c++  java
  • 指向const的指针和const指针

    1 int i = 0;
    2 const int *p1 = &i;
    3 int const *p2 = &i;
    4 int *const p3 = &i;

    上述代码中的p1和p2都是指向const的指针,表示指针指向的地址里的内容不可修改,*p1 = 1;会编译不过;p3则是const指针,表示p3指向的地址不可修改,p3 = NULL;会编译不过。

    1 int i = 0;
    2 typedef int *PINT;
    3 const PINT pInt = &i;
    4 *pInt = 1;

    上述代码中的pInt变量是const指针,而非指向const的指针,使用PINT类型是声明不出指向int类型的const指针的。

    1 int i = 0;
    2 PINT const pInt = &i;
    3 vector<int*> vecInt;
    4 vecInt.push_back(pInt);
    5 const int *pInt2 = &i;
    6 vecInt.push_back(pInt2);

    以上代码的第6行编译不过,原因如下:

    stl中的vector的push_back方法的原型是“void push_back(const _Ty& _X)”,但是VC给出该函数的原型提示是void push_back(const int * &_X);这两个其实是不同的类型,此时的_Ty其实就是typedef int *_Ty;所以push_back的参数类型是int*类型的const引用,期待的是一个指针或const指针,便是pInt2则是指向const的指针,指向const的指针不会隐式转换为const指针或指针,所以编译出错。

    1 const int **p = (const int**)0x40000000;
    2 *p = (int*)3;
    3 **p = 3;

    上述代码的第三行编译不过,可见const修饰的是最内层指针指向的内容。

    如果写成 

    1 typedef int *PINT;
    2 const PINT *p = (PINT*)0x40000000;
    3 **p = 4;
    4 *p = (PINT)3;

    则是第4行编译不过了,读者可以验证一下。

  • 相关阅读:
    C语言寒假大作战01
    C语言I作业12—学期总结
    C语言I博客作业11
    C语言I博客作业10
    C语言I博客作业09
    C语言I博客作业08
    C语言寒假大作战04
    C语言寒假大作战03
    C语言寒假大作战02
    C语言寒假大作战01
  • 原文地址:https://www.cnblogs.com/xueguangfeng/p/const_pointer_and_pointer_to_const.html
Copyright © 2011-2022 走看看