其他分享
首页 > 其他分享> > 常量和指针

常量和指针

作者:互联网

#include<stdio.h>

int main()
 {   const float pi=3.14;
     printf("%f\n",pi);
     pi=3.1415;
     return 0;
 }

常量不能被修改,否则会报错

 

指向常量的指针

#include<stdio.h>

int main()
 {
     int num=520;
     const int cnum=880;
     const int *pc=&cnum;

     printf("cnum:%d,&cnum:%p\n",cnum,&cnum);
     printf("*pc:%d,pc:%p\n",*pc,pc);
     return 0;
 }

结果

cnum:880,&cnum:000000000061FE0C
*pc:880,pc:000000000061FE0C

#include<stdio.h>

int main()
 {
     int num=520;
     const int cnum=880;
     const int *pc=&cnum;

     printf("cnum:%d,&cnum:%p\n",cnum,&cnum);
     printf("*pc:%d,pc:%p\n",*pc,pc);
     *pc=1024;
     return 0;
 }

不能用*pc修改值,因为指针被定义指向常量的指针,修改pc的指向,pc=&num;

#include<stdio.h>

int main()
 {
     int num=520;
     const int cnum=880;
     const int *pc=&cnum;

     printf("cnum:%d,&cnum:%p\n",cnum,&cnum);
     printf("*pc:%d,pc:%p\n",*pc,pc);

     pc=&num;

     printf("num:%d,&num:%p\n",num,&num);
     printf("*pc:%d,pc:%p\n",*pc,pc);
     return 0;
 }

结果

cnum:880,&cnum:000000000061FE10
*pc:880,pc:000000000061FE10
num:520,&num:000000000061FE14
*pc:520,pc:000000000061FE14

 

常量指针(让指针也不可变)

#include<stdio.h>

int main()
 {
     int num=520;
     const int cnum=880;
     int *const p=&num;
     *p=1024;
     printf("*p=%d\n",*p);
     return 0;
 }

结果

*p=1024

这时指针不能变,但*p的值可以修改,不能再写p=&cnum;

 

指向常量的常量指针(两种都不能修改)

#include<stdio.h>

int main()
 {
     int num=520;
     const int cnum=880;
     const int *const p=&cnum;
     *p=1024;
     printf("*p=%d\n",*p);

     p=&num;
     printf("*p=%d\n",*p);
     return 0;
 }

出现两个报错

#include<stdio.h>

int main()
 {
     int num=520;
     const int cnum=880;
     const int *const p=&num;

     num=1024;
     printf("*p:%d\n",*p);
     return 0;
 }

p指向的是没有const的变量,可以这样修改

结果

*p:1024

 

指向“指向常量的常量指针”的指针

#include<stdio.h>

int main()
 {
     int num=520;

     const int *const p=&num;
     const int *const *pp=&p;

     printf("pp:%p,&p:%p\n",pp,&p);
     printf("*pp:%p,p:%p,&num:%p\n",*pp,p,&num);
     printf("**pp=%d,*p=%d,num=%d\n",**pp,*p,num);
     return 0;
 }

结果

pp:000000000061FE08,&p:000000000061FE08
*pp:000000000061FE14,p:000000000061FE14,&num:000000000061FE14
**pp=520,*p=520,num=520

 

标签:const,常量,int,cnum,pc,num,printf,指针
来源: https://www.cnblogs.com/dxfDXF/p/15335202.html