当前位置:网站首页>指针常量与常量指针详细讲解
指针常量与常量指针详细讲解
2022-07-26 22:46:00 【Meme_xp】
标题:指针常量与常量指针
1.常量指针:
int a,b;
const int *p1=&a;
int const *p2=&b;
1.1记忆方法:
const在*p前面我们先读出const(常量)然后再读出指针,组合在一起就是常量指针。
1.2理解:
我们可以理解为一个"常量"的指针,并没有规定指向的是哪一个"常量",所以指针的指向可以改变。回到"常量"这个词,"常量"是不可以修改的量所以我们不能通过指针去修改这个"常量"的值。这里的常量加了引号,我们接下来会在注意事项中解释清楚。
1.3注意事项:
常量指针不能通过指针修改a的值,但是我们可以直接修改a的值。
1.3.1第一种写法:
int a=10;
const int *p=&a;
a=20;
cout<<"a="<<a<<","<<"*p="<<*p;
这种写法是没有错误的,待会儿会解释。
1.3.2第二种写法:
int a=10;
const int *p=&a;
*p=20
cout<<"a="<<a<<","<<"*p="<<*p;
编译器对于上面这种写法会报错:[Error] assignment of read-only location ‘* p’。我们来翻译这句话,大概意思是:*p分配在了只读区域。所以不支持写入,为什么这么解释?是不是和上面的理解产生了冲突。并不,因为我们可以这样理解:a本身就是一个变量,只是我们从const int *p,这个方向看过去,我就把a看成一个常量,编译器我从这个方向就要这么看。但其实a本身是一个变量不能通过 * p来改变也可以通过其他方式改变。举一个例子:
float num=3.14;
cout<<"num="<<(int)num;
很简单一个例子,num很明显就是一个float,但是我们就是要把他看成一个int。
2.指针常量:
int c;
int * const p3 =&c;
2.1记忆方法:
从表达式中可以看到int * 在const前面,int*可以代表指针,而const代表常量,组合在一起我们读作指针常量。
2.2理解:
我们知道常量是不可以修改的量。从字面意思可以看出常量修饰的是指针这两个字。所以我们不能将修改指针的值,指针的值又是一个地址,推之我们不能指针的指向(也就是指针的值)。但是可以修改变量c的值,因为并没有规定c是一个常量。
3.
当然const int * const p就是指针的指向不能改并且不能通过指针修改变量的值。但是还是可以直接通过直接访问a来修改a的值。解释见1.3
int a=10;
const int * const p=&a;
a=20;
cout<<"a="<<a<<","<<"*p="<<*p;
4.总结:
本篇文章从我个人的角度解释了我对指针与常简单的联系,如有疑问欢迎在评论区留言或者私信本人。观点经供参考,如果有错误欢迎大家的指正。
边栏推荐
- (atcoder contest 144) f - fork in the road (probability DP)
- 27shell conditional statement
- Domain name analysis and DNS configuration installation
- Proxmox VE安装与初始化
- Shell (7) case statement
- 【无标题】
- 数字图像处理重点总结复习
- Shell (9) function
- Desktop solution summary
- Harmonyos image processing application development live broadcast notes
猜你喜欢
随机推荐
33 three swordsman awk
Transport layer --------- TCP (II)
Shell programming specifications and variables
[mysql] what happens when things are executed concurrently?
Shell loop statement
21DNS域名解析
29shell函数
Use of shell (11) brackets
Summary and review of key points of digital image processing
【多态】多态的详细介绍,简单易懂
科学计算库 —— Numpy
【无标题】
shell课程总结
识别神器Mx-yolov3
Shell (10) array and bubble sort
Notes during in-depth learning (to be improved)
Shell script - backup, update and rollback of files
Identify artifact MX yolov3
Paddleocr usage example
21dns domain name resolution
![[polymorphism] the detailed introduction of polymorphism is simple and easy to understand](/img/85/7d00a0d9bd35d50635a0e41f49c691.png)







