C语言基础---const常指针的使用

来源:互联网 发布:手机如何申请淘宝直播 编辑:程序博客网 时间:2024/05/01 05:50

有一个面试题:

http://blog.csdn.net/tigerjibo/article/details/6827809

1、解释下面ptr含义和不同(好像是。。。。题干了大概意思是这样。下面应该没错)

double* prt = &value

const double* ptr = &value

double* const ptr=&value

const double* const ptr=&value

2、去掉const属性,例:

      const double value = 0.0f;

      double* ptr = NULL;

怎么才能让ptr指向value?


#include<stdio.h>/*void fun(){extern const int a=10;//error C2205: cannot initialize extern variables with block scope}*/int main(){const int a=10;int i=20;/*几种声明方式*/const int * b=&a;//b是指向常量a的指针int const * c=&a;//c与b一致 声明方式不同int * const d=&i;//d指向整型的常指针const int * const e=&a;/* 将const值赋值给非const指针: C++:int * ptr = const_cast(&r);C语言使用:int * ptr =(int*)&r; */int * f=NULL;//空地址用 NULLf=(int*)&a; //只能强制转换*f=20;//将常量赋值给非const指针会改变常量的值,表面上/* some tests:b=0;//it's ok&a=0;//不能改变内存地址 readonly? error C2106: '=' : left operand must be l-valued=0;//error C2166: l-value specifies const object*/printf(" a:%d\n addrOfa:%d\n b:%d\n c:%d\n d:%d\n e:%d\n f:%d\n fake a:%d\n a:%d\n",a,&a,b,c,d,e,f,*f,a);return 0;}

结果:

 a:10
 addrOfa:1244996
 b:1244996
 c:1244996
 d:1244992
 e:1244996
 f:1244996
 fake a:20
 a:10
Press any key to continue

更多应用:http://developer.51cto.com/art/201002/182348.htm

0 0
原创粉丝点击