const*p和*const p的区别

2025-02-25 15:37:55
推荐回答(4个)
回答1:

唯一的区别在于:p可变,*p不可变。

下面程序说明*p不可变:

int main()

{

int a;

const int* p = &a;//编译器将a看做const int型,所以该句不会出错

//*p = 1;//l-value specifies const object,虽然声明的a 没有const标记,但由于p的效果,*p不能改变

return 0;

}

下面程序说明p可变:

int main()

{

const int *p;

int a,b;

p = &a;

p = &b;

return 0;

}

扩展资料:

const int *p与int const *p用法一样。

const int *p的用法

#include

#include

#include

int main(int argc, char **argv)

{

int test1 = 1;

int test2 = 2;

const int *p;

p = &test1;

p = &test2;

test2 = 3;

//*p = 4;     error: assignment of read-only location ‘*p’

printf("%d\n", *p);

return 0;

}

执行结果 :3 ,这个好理解,如果加入被我注释掉的那一行就会报错,编译通不过,也就是说*p是常量,不可更改,但指针p还是变量,你想怎么变都可以。

执行结果 :3 ,这个好理解,如果加入被我注释掉的那一行就会报错,编译通不过,我用的是gcc version 4.4.3。也就是说*p是常量,不可更改,但指针p还是变量,你想怎么 变都可以。

#include

#include

#include

int main(int argc, char **argv)

{

int test1 = 1;

int test2 = 2;

int *const p = &test1;  //只能在声明的时候就给它赋初值,否则还是会报错的

//p = &test2; error: assignment of read-only location ‘*p’

test1 = 3;

printf("%d\n", *p);

return 0;

}

执行结果 :3 ,这样用p是常量,也就是说p所指向的地址是不可以更改的,所以当把test2的地址赋值给p时就会报错,但是p所指的地址内容是可以改变的。

回答2:

const *p // a=*p;如果a的值等于1,那么a就永远等与1,P代表的是地址,就是说这个地址是可以变化的,把内存分成1-10层楼房,那么1可以住在任何一间房子里面,就是说P是门牌号,可以变化,但是房子里面的内容不会变化

*const p // a=*p;如果a的值等于1,那么你可以重新赋值给*p=2,这个时候在a=*p,a就变成2了,就是说房子里面的内容可以变,但是门牌号不会变

Do you understand?

回答3:

一个叫常量指针,另一个叫指针常量,课本介绍指针那章最后一讲有,你自己去看嘛!!!

回答4:

这个里面p是指针啊~~~
指针指向有一个地址空间,这个里面有相应的内容。。。也就是p指向的对象