问题
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