const int *与int *const的区别

(这次又是隔了好久才开始动笔,真对不起我的开篇博客说的)
常量指针与指向常量的指针

int const* p  //指向常量的指针
const int* p  //指向常量的指针
int *const p  //常量指针

以上三个是C语言中,不怎么常用的,但是当学到C++时,就很容易混淆,首先 const int* p和int const* p是等价的,都表示的是p的值不能改变,但是p(地址)是可以改变的。
(1)常量指针 int* const p

#include <stdio.h>
#include <stdlib.h>
int main()
{
int p1=10;
int* const p=&p1;
printf("%d ",*p);  //此时输出*p的值是10
*p=20;
printf("%d ",p1);  //此时输出p1是20,因为通过*p修改了p1的值
system("pause");
return 0;
}

就是说不能修改这个指针所指向的位置,但是这个指针所指位置的值是可以被修改的。
(2)指向常量的指针 const int* p

#include <stdio.h>
#include <stdlib.h>
int main()
{
int p1=10;
int p2=20;
const int* p=&p1;
printf("%d ",*p);  //输出10
/* *p=40;
printf("%d ",p1) */ //不能修改指针指向的地址来改变指针指向的值,输出会报错,因此注释掉
p=&p2;
p2=30;
printf("%d ",*p);  //输出30
system("pause");
return 0;
}

不可以通过修改地址来改变这个指针所指向的值
(3)指向常量的常量指针
对于指向常量的常量指针,基本能修改指针的所指向的位置,也不能修改指针指向的值

今天的分享结束

发布了33 篇原创文章 · 获赞 13 · 访问量 1070

猜你喜欢

转载自blog.csdn.net/Vicky_Cr/article/details/102327173