const int * p 和 int const * p 和 int * const p 的区别

时间:2023-03-09 20:19:08
const int * p 和  int  const * p 和 int * const p 的区别

首先注意,const int * p 和int const *p 是一样的,并且不管是不是*p,即使const int i和int const i也是一样的,所以我们接下来只讨论int const * p和int * const p的不同

对于这种问题,我们只用将const 的位置固定,然后再看后面的东西,一般规则是后面的东西不能在进行赋值或者修改.例如下面:

#include<stdio.h>

int main(int argc,char *argv[])
{
int i = 10;
int j = 1;
int const *p2 = &i;
int *const p3 = &j;
p2 = &j; //这句没问题,因为const是对 *p2 进行限制的
*p3 = 20; //这句也没问题,同理,const是对p3进行操作的
*p2 = 30; //这句错了,原因就是已经用const修饰了,不能再次改
p3 = &j; //同上,错误
return 0; }

我们编译下再看下效果:

const int * p 和  int  const * p 和 int * const p 的区别

错误提示:”read-only”,现在有没有对这个问题有理解呢,觉得const怎么样呢?那么我再说一个问题,不知道为什么的问题:

#include<stdio.h>

int main()
{
const int a = 5;
int *p = (int *)&a;
*p = 10;
printf("a:%d\n",a);
}

const int * p 和  int  const * p 和 int * const p 的区别

对,这个结果可是让我吃惊了,为什么呢?欢迎评论交流.

版权声明:本文为博主原创文章,未经博主允许不得转载。