c语言---const搭配指针问题

来源:互联网 发布:mac 视频特效 编辑:程序博客网 时间:2024/06/11 11:27


如果const在'*'左边,则表示指针指向的变量的值不可变;   保存的值不变。


如果const在'*'右边,则表示指针的值是不可变的;  即是地址不变。


void test()
{
int a = 10;
int b = 20;


int * const p1 = &a;
printf("p1=%d\n",*p1); //10

//int * const p1; p1 read only
//p1 = &a;

//p1 = &b; error 

a = 100;
printf("p1=%d\n",*p1); //100


*p1 = 1000;
printf("p1=%d\n",*p1); //1000



int const *p2;
p2 = &b;
printf("p2=%d\n",*p2); //20

b = 200;
printf("p2=%d\n",*p2); //200


p2 = &a;
printf("p2=%d\n",*p2); //1000


//*p2 = 30; error


}



原创粉丝点击