874
京东网上商城
[面试题]const与指针
(1)const int *p; int const *p2;
#include <iostream> #include <stdio.h> #include <string.h> using namespace std; int main(){ int a = 3; int b = 4; const int *p; p= &a; int const *p2; p2 = &b; //*p = 5; error: assignment of read-only location '* p' //*p2 = 5; error: assignment of read-only location '* p2' p = &b; printf("%d\n",*p); //综上可以知道:指针不是常量,指针所指向的内存区域是常量。 }
*p = 5;
报错:error: assignment of read-only location '* p'
*p2 = 5 ;
报错:error: assignment of read-only location '* p2'
意思很明确:*p *p2都是常量不可以更改。指针p和p2都是变量可以随意指向任意地址。p = &a; p = &c;都可以。
(2)int *const p3
#include <iostream> #include <stdio.h> #include <string.h> using namespace std; int main(){ int a = 3; int b = 4; //int *const p3 error:uninitialized const 'p3' 只能在声明的时候就给它赋初值,否则还是会报错的 int *const p3 = &a; //p3 = &b; error: assignment of read-only variable 'p3' *p3 = 8; printf("%d\n",*p3); //综上可以知道:指针是常量,所指向的内存区域是不能更改的。指针所指向的内存区域不是常量,可以修改。 }
int *const p3;
报错:error:uninitialized const 'p3' 没有对p3进行初始化。
p3 = &b;
报错:error: assignment of read-only variable 'p3' 指针p3是常量,不可以更改指针指向的地址。
*p3 = 8;
*p3是变量,可以更改指针p3指向的值。
综上可以知道:指针p3是常量,不可以更改指针指向的地址。*p3是变量,即指针指向的是变量,可以更改指针p3指向的值。
(3)const int *const p3
#include <iostream> #include <stdio.h> #include <string.h> using namespace std; int main(){ int a = 3; int b = 4; const int *const p3 = &a; //int *const p3 error:uninitialized const 'p3' //p3 = &b; error: assignment of read-only variable 'p3' //*p3 = 8; error: assignment of read-only location '*(const int*)p3' printf("%d\n",*p3); }
int *const p3;
报错:error:uninitialized const 'p3' 没有对p3进行初始化。
p3 = &b;
报错:error: assignment of read-only variable 'p3' 指针p3是常量,不可以更改指针指向的地址。
*p3 = 8;
报错:error: assignment of read-only location '* (const int*)p' *p3是常量,不可以更改指针p3指向的值。
综上可以知道:指针p3是常量,不可以更改指针指向的地址。*p3是常量,即指针指向的是常量,不可以更改指针p3指向的值。
具体总结:
int* p = 4; //non-const pointer,non-constdata const char* p = &p; //non-constpointer,const data; char* const p = &p;//constpointer,non-const data; const char* const p = &p; //constpointer,const data;
关于定义的阅读,一直以为这段解释很不错了已经,即以*和const的相对位置来判断:
const语法虽然变化多端,但并不莫测高深。如果关键字const出现在*左边,表示被指物是常量;如果出现在*右边,表示指针自身是常量;如果出现在*两边,表示被指物和指针两者都是常量。
如果被指物是常量,有些程序员会将关键字const写在类型之前,有些人会把它写在类型之后、*之前。两种写法的意义相同,所以下列两个定义相同:
const Widget* w; Widget const* w;
其实很简单,const和*的优先级相同
且是从右相左读的,即“右左法则”
其实const只是限定某个地址存储的内容不可修改
比如int*p;读作p为指针,指向int,所以p为指向int的指针
int*const p;读作p为常量,是指针,指向int,所以p为指向int的常量指针, p不可修改
int const *p;p为指针,指向常量,为int,所以p为指向int常量的指针, *p不可修改
int ** const p; p为常量,指向指针,指针指向int,所以p为指向int型指针的常量指针,p不可修改
int const**p; p为指针,指向指针,指针指向常量int,所以p为指针,指向一个指向int常量的指针, **p为int,不可修改
int * const *p ; p为指针,指向常量,该常量为指针,指向int,所以p为指针,指向一个常量指针,*p为指针,不可修改
int ** const *p; p为指针,指向常量,常量为指向指针的指针,p为指针,指向常量型指针的指针,*p为指向指针的指针,不可修改
int * const **p; p为指针,指向一个指针1,指针1指向一个常量,常量为指向int的指针,即p为指针,指向一个指向常量指针的指针, **p为指向一个int的指针,不可修改
最后更新:2017-04-03 05:40:17