指向常量的指针与常量指针(A pointer to a constant And A constant pointer)

指向常量的指针(A pointer to a constant)

 可以改变指针中存储的地址,但不允许使用指针改变她指向的值;

long value = 9999L;
const long *ptrvalue = &value;         //Defines a pointer to a constant
*ptrvalue = 8888L;         //Error - attempt to change const location

//ptrvalue指向的值不能改变,但可以对value进行任意操作。
 value = 7777L;//改变了ptrvalue指向的值,但不能使用ptrvalue指针做这个改变。

//当然,指针本身不是常量,所以仍然可以改变它指向的值:
 long number = 8888L;
 ptrvalue = &number;                      //OK-changing the address in ptrvalue
        
 //这会改变指向number的ptrvalue中的地址,仍然不能使用指针改变它指向的值。

完整的代码:

#include<stdio.h>
#include<stdbool.h>
int main(void)
{
    int value = 999;
    const int *ptrvalue = &value;
    printf("%d\n",*ptrvalue);
    printf("%p\n",ptrvalue);
    
    int number = 888;
    
    ptrvalue = &number;
    printf("%d\n",*ptrvalue);
    printf("%p\n",ptrvalue);

    return 0;
 }

常量指针(A constant pointer)

允许使用指针改变它指向的值,但不允许改变指针中存储的地址

//是指针总是指向相同的对象:
  int count = 43;
  int * const ptrcount = & count;            //Define a constant pointer
//第二条语句声明并初始化了ptrcount,指定该指针存储的地址不能改变

  int item = 34;
  ptrcount = &item;         //Error-attempt to change a constant pointer
 
//但使用ptrcount,仍可以改变ptrcount指向的值:
    *ptrcount = 345;         //OK -changes the value of count

 完整的代码:

 #include<stdio.h>
 int main(void)
 {
     int number = 43;
     int * const ptrnumber = &number;
     printf("%d\n",*ptrnumber);
     printf("%p\n",ptrnumber);
     printf("%p\n",&number);
    
     *ptrnumber = 34;
     printf("%d\n",*ptrnumber);
     printf("%p\n",ptrnumber);
     printf("%d\n",number);
     printf("%p\n",&number);

     return 0;
  }

指向常量的常量指针(Constant pointer to constant)

 int item =25;
 const int *const ptritem = &item;

 //ptritem是一个指向常量的常量指针,所以所有的信息都是固定不便的。不能改变存储在ptritem中的地址,也不能使用ptritem改变它指向的内容。但是可以直接修改item的值。如果希望所有的信息都固定不变,可以把item指定为const。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值