Why can not so declare the matrix?
const int** A = new int* [n]; int** A = new const int* [n]; Formally, you just lose const qualifiers with implicit conversion. If you allow such conversions to be implicit - you can get a lot of trouble, for example, you can change constant variables without any problems. Therefore, the compiler must explicitly say that you understand what you are doing, and take responsibility for yourself - using const_cast :
const int** A = const_cast<const int**>(new int* [n]); int** B = const_cast<int**>(new const int* [n]); And yet - this is not an ad , which is really only
const int** A; int** B; You already initialize the declared variables.
If you have some type T , then you can assign a pointer of type T * pointer of type const T * . for example
int i = 10; int *p = &i; const int *cp = p; That is, when type T is the same in both cases , but it differs only in the qualifier for type T In this case, an implicit conversion to pointers is applied.
Again. Note that the type of T pointed to by pointers is the same. Only the type pointed to by the left pointer adds the const qualifier.
Now consider this announcement
const int** A = new int* [n]; On the left side of this declaration, we have a pointer that points to an object of type const int * . You can simplify this expression using a typedef declaration.
For example,
typedef const int * T; or
using T = const int *; Then you can rewrite the sentence as
T * A = new int* [n]; And what type of object is the object pointed to by the pointer on the right side of the assignment sign?
If we reintroduce the typedef declaration, we get
typedef int * T1; or
using T1 = int *; As a result, we will have
T *a = T1 *tmp; Types T and T1 are different types, so there is no implicit pointer conversion from one type to another type. The basic types of these pointers are different. In one case, the base pit is const int *, and in the other case it is int * .
You could write your original ad as follows
int * const * A = new int* [n]; and then it would have compiled successfully. Indeed, on the left and right sides there are pointers to the type int * . Both pointers have the same basic type of object to which they point. Only the left hand side added the const qualifier to this type of object, as was described at the very beginning of my answer.
That is, if you enter a typedef declaration
typedef int * T; or
using T = int *; then you can write
const T * A = new int* [n]; Only in this case is the constant pointer itself to int , that is, int * const , and not the type of object pointed to by the pointer, as in the case of declaring const int * .
A similar problem holds for your second ad.
Type conversion forgot:
const int** A1 = (const int**) new int* [10]; int** A2 = (int**) new const int* [10]; Source: https://ru.stackoverflow.com/questions/590160/
All Articles