简体   繁体   中英

c++ const for pointer to pointer

a pointer to a constant int. I may change the pointer, but I may not change the value:

const int* a;

a constant pointer to an int. I may not change the pointer, but I may change the variable's value:

int* const a;

now, how do things look like if I'm dealing with a pointer to a pointer?

int** a;

how do I:

a) declare a const pointer to a non-const pointer to a non-const int

b) declare a non-const pointer to a const pointer to a non-const int

c) declare a non-const pointer to a non-const poiinter to a const int?

a) declare a const pointer to a non- const pointer to a non- const int

int ** const a = nullptr;

Note that, since the pointer above is const -qualified it has to be initialized at the declaration. Otherwise, it won't compile.

b) declare a non- const pointer to a const pointer to a non- const int

int * const *b;   

c) declare a non- const pointer to a non- const pointer to a const int

const int **c;

The pattern is, for a const pointer:

T * const ptr; // const pointer to T

and for a non- const pointer:

T * ptr; // non-const pointer to T

Then, select the proper pattern above for the outtermost pointer and replace T accordingly for the innermost pointer (ie, the deepest one buried in the type):

  • Non- const pointer to a non- const int : T = int * .
  • const pointer to a non- const int : T = int * const .
  • Non- const pointer to a const int : T = const int * .

It's all about where the const is placed relative to the * : if const is on the left then what's pointed to is const , if const is on the right of * then what's pointing is const .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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