简体   繁体   English

指向地址或指向值的指针的常量指针

[英]constant pointer to an address or pointer to a value

Do int const *a and const int *a mean that "a is a integer pointer to a constant value" and "a is a pointer to a constant address", respectively , or is it viceversa? int const *aconst int *a表示“a是指向常量值的整数指针”和“a是指向常量地址的指针”,还是反之?

This was asked to me in an interview. 这是在接受采访时向我询问的。 After reading a lot about the same I am still very much confused regarding it. 在阅读了很多关于同样的事情之后,我仍然非常困惑。

int const *a;

which is equivalent to: 这相当于:

const int *a;

means a is a pointer to a const int object. 表示a是指向const int对象的指针。

When the const hops over the type keyword ( int ), the meaning doesn't change. const跳过type关键字( int )时,含义不会改变。

The meaning changes when the const hops over the * . const跳过*时,含义会发生变化。

const int *a; /* The int is const */
int const *b; /* The int is const */
int *const c; /* The pointer is const */
  • const int *a - a is writable (can point to a different thing), *a is not writable (cannot write to pointed-to thing) const int *a - a是可写的(可以指向不同的东西), *a是不可写的(不能写入指向的东西)
  • int const *a - same as above int const *a - 与上面相同
  • int * const a - a is not writeable (cannot point to a different thing), *a is writable (can write to pointed-to thing) int * const a - a不可写(不能指向不同的东西), *a是可写的(可以写入指向的东西)
  • const int * const a - neither a nor *a are writable const int * const a - 既不a也不是*a都是可写的
  • int const * const a - same as above int const * const a - 与上面相同

If you read the first two cases as 如果你读前两个案例为

const int (*a)
int const (*a)

it's clear that the const is modifying the int type specifier; 很明显, const正在修改int类型说明符; we're pointing to a constant integer . 我们指的是一个常数整数

If you read the third case as 如果你读第三个案例为

int (* const a)

then the const is modifying the pointer declarator *a ; 那么const正在修改指针声明符*a ; we have a constant pointer to an integer. 我们有一个指向整数的常量指针

Then you read the final two cases as 然后你读了最后两个案例

(const int) (* const a)
(int const) (* const a)

then it's clear that we have one const modifying the type specifier and the other modifying the pointer, so we have a constant pointer to a constant integer . 那么很明显我们有一个const修改类型说明符而另一个修改指针,所以我们有一个指向 常量整数常量指针

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM