Possible Duplicate:
why isnt it legal to convert (pointer to pointer to non-const) to a (pointer to pointer to a const)
Hi I have the following code, but cannot wrap my head around why this doesn't work - I get an error saying "cannot convert from int** to const int**". However, if I change the first argument of printValues to be "const int *const * myArray", it all works fine. I know I probably shouldn't be using the one below anyway, but I don't understand why it doesn't compile at all. Can you not have a pointer to a pointer to a constant integer without declaring it constant in main()?
#include <iostream>
int printValues(const int ** myArray, const long nRows, const long nCols)
{
for (long iRow = 0; iRow < nRows; iRow++)
{
for (long iCol = 0; iCol < nCols; iCol++)
{
std::cout << myArray[iRow][iCol] << " ";
}
std::cout << "\n";
}
return 0;
}
int main()
{
const long nRows = 5;
const long nCols = 8;
int** myArray = new int* [nRows];
for (long iRow = 0; iRow < nRows; iRow++)
{
myArray[iRow] = new int [nCols];
}
for (long iRow = 0; iRow < nRows; iRow++)
{
for (long iCol = 0; iCol < nCols; iCol++)
{
myArray[iRow][iCol] = 1;
}
}
printValues(myArray, nRows, nCols);
return 0;
}
int **
is: "a pointer to a pointer to an integer".const int **
is: "a pointer to a pointer to a constant integer".A far-fetched analogy:
You can only put a cookie inside a jar that is not closed.
Now, think of replacing the second note with a photocopy of the first note. Do you have any guarantee that the ultimate jar that this note points to will be closed and cannot accept any cookies? The use of const
is a contract and you cannot meet this contract by going through the indirection of two references.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With