Search code examples
c++pointersmultidimensional-arrayconstantsparameter-passing

How to pass a two-dimensional array of pointers as const?


If I create a two-dimensional array of pointers and pass it to a function:

int main()
{
    int* array[2][2];

    int a = 5;
    int b = 10;
    array[0][0] = &a;
    array[1][1] = &b;

    test(array);
}

How can I define this function so that none of the following 3 statements are possible?

void test(int* array[2][2])
{
    int c = 20;

    // statement 1:
    *(array[0][0]) = c;

    // statement 2:
    array[1][1] = &c;

    // statement 3:
    int* array2[2][2];
    array = array2;
}

I tried this:

void test(int const * const array[2][2])
{
    int c = 20;

    // statement 1:
    *(array[0][0]) = c;     // is no longer possible

    // statement 2:
    array[1][1] = &c;       // is no longer possible

    // statement 3:
    int* array2[2][2];
    array = array2;         // is still possible
}

Since const works from right to left, the first const prohibits changes to the int values pointed to by the pointers of the array through dereference of these pointers (statement 1) and the second const prohibits changes to the pointers themselves (statement 2).

But I couldn't find out how to make the array itself const, so that the variable named "array", which in my understanding is a pointer to the first element of the array, can't be changed to point to another first element/array (statement 3).

Help much appreciated. Thank you.


Solution

  • void test(int const * const array[2][2])
    

    decays to:

    void test(int const * const (* array)[2])
    

    which can be const with:

    void test(int const * const (* const array)[2])