int i = 10;
intconst *const cp = &i;
intconst **cp2 = &cp;
//if i declare cp2 as a pointer to const i cannot modify nor cp nor i, why it is //illegal ?
1 2 3 4 5 6
//but if i add another const qualifier
int i = 10;
intconst *const cp = &i;
intconst *const *cp2 = &cp; //why now it is legal ?
can you help me with some advice for pointer to pointer to const ? i usally read them from the right to the left and put the const on the right
cp cp is a...
*const ...const pointer to a...
intconst ...constint.
Reading intconst **cp2 from right to left:
1 2 3 4
cp2 cp2 is a...
* ...non-const pointer to a...
* ...non-const pointer to a...
intconst ...constint.
Since cp is a const pointer &cp will give you a pointer to a const pointer, but cp2 is a pointer to a non-const pointer so obviously this is not allowed. If it was allowed it would be possible to modify cp through cp2 despite that cp is const.
1 2 3 4 5 6 7 8
int i = 10;
intconst *const cp = &i;
intconst **cp2 = &cp; // Imagine this was not an error.
// This would modify the const pointer cp,
// which shouldn't be modified because
// that's what const means.
*cp2 = 0;
intconst *const cp = &i;
You cannot change the pointer cp, nor the value that it points to. Okay.
intconst **cp2 = &cp;
cp2 is a pointer to a pointer to an int. You can change cp2, and you can change *cp2, but you can't change **cp2. In other words, you can't change the int, but you can change the point to it, and the pointer to the pointer.
However, you'd initializing it to point to cp, and cp ( the pointer to int) can change. This is why it's illegal.