C++ - can't assign top-const pointer to another non-const pointer

梦想与她 提交于 2021-02-10 16:24:28

问题


My compiler gives me error when I try to compile this. It tells me that

p1 = p2;

from this :

int main ()
{
    int var, *p1;
    const int *p2 = &var;
    p1 = p2;
    return 0;
}

is invalid conversion (const int --> int). Var is not const so it shouldn't hinder. I get that p2 can't be used to change value of var, but I think it should just assign adress if var to p1.

I know that this:

    p1 = &var;

yields the same result, but what interests me is why the former doesn't work. It is just out of curiosity about inner workings of C++.

Sorry about my languages (C++ and English), I'm not programmer, nor native speaker.

Thank you in advance.


回答1:


Emm... Declared type of p1 is int *. And type of p2 in const int *.
So you want to assign const int* to int*, which isn't allowed.
p1 = &var is allowed, because var has int type, not const int.




回答2:


You simply cannot assign a pointer to constant to another pointer. For example P1 is pointer which is pointing to a constant value, If you give the address of this const int to another pointer, So that can modify the the INT which we want to be constatnt.



来源:https://stackoverflow.com/questions/45067435/c-cant-assign-top-const-pointer-to-another-non-const-pointer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!