指针常量和常量指针概述

const

const是constant的简写,只要一个变量前面用const来修饰,就意味着该变量里的数据可以被访问,不能被修改。也就是说const意味着“只读”。任何修改该变量的尝试都会导致编译错误。const是通过编译器在编译的时候执行检查来确保实现的(也就是说const类型的变量不能改是编译错误,不是运行时错误。)所以我们只要想办法骗过编译器,就可以修改const定义的常量,而运行时不会报错。

规则:
const离谁近,谁就不能被修改;
因为常量在定义以后就不能被修改,所以使用const定义变量时必须初始化。

const point

声明指针时,可以在类型前或后使用关键字const,也可在两个位置都使用。三种定义形式如下:

Pointer to constant
const int *ptr;
int const *ptr;
Constant pointer to variable
int *const ptr;
constant pointer to constant
const int *const ptr;

各个含义如下:

  1. const int * pOne;
    You cannot change the value pointed by ptr, but you can change the pointer itself.
  2. int * const pTwo;
    You cannot change the pointer p, but can change the value pointed by ptr.
  3. const int *const pThree;
    You can neither change the value pointed by ptr nor the pointer ptr.

重点理解

指针和 const 谁在前先读谁 ;
*象征着地址,const象征着内容;
谁在前面谁就不允许改变。

例如:
int const *p1 = &b; //const 在前,定义为常量指针
int *const p2 = &c; // *在前,定义为指针常量

常量指针是指指向常量的指针,顾名思义,就是指针指向的是常量,即,它不能指向变量,它指向的内容不能被改变,不能通过指针来修改它指向的内容,但是指针自身不是常量,它自身的值可以改变,从而指向另一个常量。

指针常量是指指针本身是常量。它指向的地址是不可改变的,但地址里的内容可以通过指针改变。它指向的地址将伴其一生,直到生命周期结束。有一点需要注意的是,指针常量在定义时必须同时赋初值。

示例

常量指针

指向常量的指针,指针的地址可以变,指针指向的内容不能变。

#改变指针b指向地址的内容
int main()
{
	int a = 2;
	int const *b = &a;
	*b = 3;          //报错:b是常量指针,指向的内容不能变
	printf("albert:%d\n",a);
}

#改变指针b的指向
int main()
{
	int a = 2;
	int b = 3;
	int const *c = &a;
	printf("albert:%p\n", c);    
	c = &b;
	printf("albert:%p\n",c);
}

指针常量

指针是一个常量,指针的地址不能变,指向的内容可以变。

int main()
{
	int a = 2;
	int b = 3;
	int *const c = &a;
	printf("albert:%p\n", c);
	c = &b;                     //报错:指针常量,指针的地址不能变
	printf("albert:%p\n",c);
}

int main()
{
	int a = 2;
	int b = 3;
	int *const c = &a;
	*c = 4;
	printf("albert:%d\n",*c);   //4
}

————
2022/08/02
家中

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值