Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why cant int** be converted to const int** in c++ [duplicate]

Tags:

c++

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;
}
like image 762
Dave Heath Avatar asked Jun 21 '11 16:06

Dave Heath


1 Answers

  • 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:

  • a note that describes the location of another note that describes the location of a jar
  • a note that describes the location of another note that describes the location of a closed jar

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.

like image 194
Ates Goral Avatar answered Sep 28 '22 05:09

Ates Goral