Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointing to a const pointer (or a pointer to a const)

Tags:

c++

pointers

I have this code:

#include <iostream>

int main(){

    int v1 = 20;

    int *p1 = &v1;
    int **p2 = &p1;

    return 0;
}

What I want to do here is pointing a pointer to another pointer, and it works fine in this case.

I make p1 to a const pointer OR a pointer to a const:

int *const p1 = &v1; OR
const int *p1 = &v1;

Now my code does not work. Considering the first case. int *const p1 = &v1;. Here is my updated code, which I think should be right:

#include <iostream>

int main(){

    int v1 = 20;

    int *const p1 = &v1;
    const int **p2 = &p1;

    return 0;
} 

Making the pointer itself const means that it cannot point to another object, but the value of that object which it was pointing can be changed. So if I want to point another pointer to the previous pointer p1, I need to make sure that this second pointer cannot be used to change the value of p1 So I make it (p2) a pointer to a const. But it does not work.

Error: : invalid conversion from 'int* const*' to 'const int**' [-fpermissive]

Similarly, the second case fails too. My code which I think should be right:

#include <iostream>

int main(){

    int v1 = 20;

    const int *p1 = &v1;
    int **p2 = &p1;

    return 0;
} 

Making a pointer point to a const means that the pointer cannot be used to change the value of the object which it was pointing to. However, the pointer can change it's own value, that is it can point to other objects. Since I can change the value of the pointer, the second pointer need not to be pointing to a const.

Error: invalid conversion from 'const int**' to 'int**' [-fpermissive]

I am using the GNU CC Compiler I am new to C++ and I am lost. I would like to know how to point pointers to other pointer which are involved with const.

like image 324
wingerse Avatar asked Feb 11 '23 11:02

wingerse


1 Answers

Your first rewrite did not work, because you tried to assign an address of a constant pointer to a pointer-to-pointer where the final "pointee" (i.e. the int) is constant, rather than the pointer in the middle. In other words, if C allowed this

int *const p1 = &v1;
const int **p2 = &p1; // Not allowed

it should allow this:

*p2 = &v2; // This would be legal.

However, this would have modified the pointer p1, which is allegedly constant.

Here is what you need to change for the first rewrite to work:

int *const p1 = &v1;
int * const *p2 = &p1;

Note how const is moved from before the declaration to between the asterisks. Now you are making a pointer to a constant pointer to int.

Your second rewrite fails because it drops const-ness altogether. To fix it, put const back at the beginning of the declaration:

const int *p1 = &v1;
const int **p2 = &p1;
like image 175
Sergey Kalinichenko Avatar answered Feb 14 '23 00:02

Sergey Kalinichenko