常量指针和指向C中常量的指针之间的差异

时间:2016-10-03 03:28:01

标签: c pointers const

我是C的新手。有人可以向我解释下列之间的区别吗?在使用和概念方面。

int *const p= &x;

int const *p= &x; 

const int *const p= &x;

或指针用法的任何其他变体,可以帮助我完全理解这个概念。

1 个答案:

答案 0 :(得分:1)

constness适用于1)指针本身 - 是否可以在初始化后更改为指向其他内容,以及2)指针指向的数据 - 数据是否可以通过指针更改。

int *const p= &x;   // p is const pointer to non-const data - p cannot change to point to something else, but you can change what it points to

int const *p= &x;   // p is non-const pointer to const data - p can change to point to something else, but what it points to cannot be changed

const int *const p= &x; // p is const pointer to const data - p cannot change to point to something else, and what it points to cannot be changed