سؤال

I am learning const pointers and values, I get however a problem with assignment ptr2 = &x, error C2440: '=' : cannot convert from 'const int *' to 'int *'. Why? ptr2 is not constant so i can change address it's pointing to, x is const but I don't change its value. I am confused.

const int x = 10;
int y = 20;
int * const ptr1 = &y; // const pointer must be initialized
int *ptr2 = &y;
cout << *ptr1 << endl;
*ptr1 = 5; // changes content of the address
cout << *ptr1 << endl;
ptr2 = &x; // changes address pointed to by ptr2,  not content of x!
cout << *ptr2 << endl;
هل كانت مفيدة؟

المحلول

There is a difference between const pointer and const value:

int * px; // pointer to an int
int * const px2; // constant pointer to an int
int const * px3; // pointer to a constant int
int const * const px4; // constant pointer to a constant int.

Your pointer can only point to the same type, or at least to a type with less restrictions.

int x = 1;
int const y = 2;
int const * px = &x; // fine, as const is more restrictive
int * py = &y; // Wrong -> you'd lose the const

So, if you have a const int, your pointer has to be a const int as well. Wether or not the pointer is constant is a different story

نصائح أخرى

ptr2 is a pointer to an int, while &x yields a reference to a const int. Your compiler recognizes that you are trying to set a pointer-to-non-const to a const value. Since this could allow you to change a const value, this is considered an error.

If this was possible, nothing would prevent you from doing *ptr2 = 7; on the next line, which would indeed modify a const object. Even worse, nothing would prevent you from passing such ptr2 into a function taking an int*, which would have no way of knowing it points to a const int.

ptr2 is a pointer to int. Strictly speaking it is a pointer to an integer that may be changed. x on the other hand is an integer that may not be changed. If you were allowed to let ptr2 point to x, you were allowed to change x through ptr2:

*ptr2 = 77; //ok, since ptr2 points to a changeable int.

So it is not the problem that ptr2 may not be redirected to point somewhere else. It is only that it may not be redirected to point to something that is not compatible with the type it points to.

The type of the expression &x is const int*, and you can't assign that to something of type int* (like ptr2).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top