Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using double pointers with const

Suppose we have

int *p1;
const int **pp2= &p1;
const int n=13;

// Which means we can't use pp2 to modify the value of the //variable whose address is stored in * pp2. * pp2 stores the address of some variable (n in this case below)

The book which I am reading -C++ primer says the following statement is perfectly legal

*pp2=&n;

I feel the above statement violates the matter written in comments above.

Could somebody please help clear this. Thanks a lot

like image 463
MathMan Avatar asked Feb 05 '23 16:02

MathMan


2 Answers

It helps to understand it with a simple example. When you write the declaration below:

const int *p;

It says *p is constant not p. p can store any address pointing to constant integer.

Similarly const int **p; says pointer to pointer to a constant int. You can change p and *p but not **p. *p can hold any address pointing to constant integer like &n in your case and you can change *P with any addresses pointing to constant integer.

like image 143
manu Avatar answered Feb 08 '23 15:02

manu


The type of &n is int const *.
The type of *pp2 is int const *.

The const qualifies the pointee, not the pointer, in this case.

So assigning one to the other is perfectly valid. The comment you quoted may be wrong, and should perhaps say:

// Which means we can't use **pp2 to modify the value of the
// variable whose address is stored in *pp2.

To elaborate :

int *p1;

The above creates a variable named p1 that can store the address of an int. It's type is int*. This statement doesn't initialize it, and so it hold an unspecified address (the value it can hold).

const int **pp2= &p1;

The above attempts to create and assign to a variable name pp2. It's type is int const ** and the statement tries to assign it the address of p1. Now the expression &p1 has the type int **, and the assignment fails, since the const qualifications mismatch.


As you can see, the code is in complete alignment with the (possibly corrected) statements.

like image 21
StoryTeller - Unslander Monica Avatar answered Feb 08 '23 16:02

StoryTeller - Unslander Monica