Possible Duplicate:
why isnt it legal to convert (pointer to pointer to non-const) to a (pointer to pointer to a const)
I have am writing a function which takes a 2D array as input, and does not change the underlying values, and I wanted to explicitly specify this in the function declaration. I am a bit confused about this code (which is obviously just a minimal dummy code to illustrate my question):
int doNotChangeA(int const *a){
return a[0]+3;
}
int doNotChangeC(int const **c){
return c[0][0]+3;
}
int main(){
int *a= new int[1];
a[0]= 5;
int b= doNotChangeA(a);
delete []a;
int **c= new int*[1];
c[0]= new int[1];
c[0][0]= 6;
int d= doNotChangeC(c);
delete []c[0];
delete []c;
return 0;
}
This code produces a compilation error:
cst.cpp:19: error: invalid conversion from ‘int**’ to ‘const int**’
cst.cpp:19: error: initializing argument 1 of ‘int doNotChangeC(const int**)’
So, I am a bit confused - why is the first part (non-const 1D array passed to doNotChangeA) allowed and the second (non-const 2D array passed to doNotChangeC) not allowed?
Basically what I want to do is have c be int** which points to non-const values as I want to do whatever I want with it before and after calling doNotChangeC. Of course, I could change doNotChangeC to just take int** instead of int const** and this would "fix" the problem, but I want to explicitly show that doNotChangeC does not change the underlying 2-D array.
Is the right thing to do:
int d= doNotChangeC( const_cast<int const**>(c) );
This compiles fine, but I am confused why is this not required for the first part, i.e. 1-D array (doNotChangeA) ?
Thanks