5

Can some one explain me a point in my following program The following program i wrote to understand what is meant by int * const * var;

#include "iostream"

using namespace std ;

int main(){

int a = 2;

int  * const   x = &a;
int * const * p = &x;

cout << **p;
return 0;
}

The output of this program is 2 .

My point of concern is p is pointer to a constant pointer to an int which is how i am using it , but i always studied that to store a pointer you need pointer to a pointer . How is this program working then . Should'nt i have used

int * const **P

as this would mean P could be containing address of some pointer .

I dont know why my code works :)

1
  • p is already a pointer to pointer. Just look at its declaration. Commented Jan 10, 2015 at 9:30

4 Answers 4

8
  1. int * const is a "const pointer to an int".
  2. int * const * is a "pointer to a const pointer to an int".

Type 2 is a pointer to a pointer. More specifically, it's a pointer to a const pointer. That's great, because the pointer you want to point to (x) is const. Since x is of type 1, taking the address of it gives you a pointer of type 2.

int * const ** would be a "pointer to pointer to const pointer to int". Count how many "pointer"s there are. Three! In fact, that's what you would get if you were to take the address of p with &p.

Sign up to request clarification or add additional context in comments.

3 Comments

@SohamChowdhury Pointers quickly become second nature with a little bit of practice. I have little boxes with arrows pointing between them in my head.
But remember, as soon as you can see three stars, it's time for a day of rest.
@DanielFischer "By the seventh day God had used a pointer to a pointer to a pointer; so on the seventh day he rested from all his work. Then God blessed the seventh day and made it holy, because on it he rested from all the indirection he had done." - Pretty sure that's how it goes.
2
  • to store a pointer you need pointer to a pointer

Apparently you think that const pointer is somehow not a pointer. You are wrong. const is just indicator of immutability. Therefore pointer to const pointer is pointer to pointer

Comments

0

x is of type int* const and suppose x be of type some ABC. so pointer to x is declared as ABC *p=&x;

which is equivalent to int* const *p=&x;

Comments

-1

I think this helps in intuiting the statement. substitute the * with pointer and read the statement backwards.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.