常量指针与指向常量的指针 [英] Constant pointer vs Pointer to constant

查看:93
本文介绍了常量指针与指向常量的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道

const int* ptr;

int * const ptr; 

及其工作方式.

我很难理解或记住这一点. 请帮忙.

It is pretty difficult for me to understand or keep remember this. Please help.

推荐答案

const int* ptr; 

声明ptr指向const int类型的指针.您可以修改ptr本身,但不能修改ptr指向的对象.

declares ptr a pointer to const int type. You can modify ptr itself but the object pointed to by ptr shall not be modified.

const int a = 10;
const int* ptr = &a;  
*ptr = 5; // wrong
ptr++;    // right  

int * const ptr;  

声明ptr指向int类型的const指针.不允许修改ptr,但不能修改ptr指向的对象.

declares ptr a const pointer to int type. You are not allowed to modify ptr but the object pointed to by ptr.

int a = 10;
int *const ptr = &a;  
*ptr = 5; // right
ptr++;    // wrong

通常,我希望这样的声明使之易于阅读和理解(从右到左阅读):

Generally I would prefer the declaration like this which make it easy to read and understand (read from right to left):

int const  *ptr; // ptr is a pointer to constant int 
int *const ptr;  // ptr is a constant pointer to int

这篇关于常量指针与指向常量的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆