如何将一个二维指针数组作为常量传递?

3
如果我创建一个指针的二维数组并将其传递给函数:
int main()
{
    int* array[2][2];

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

    test(array);
}

我该如何定义这个函数,以便不能实现以下三种语句中的任何一种?

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;
}

我尝试了这个:
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
}

由于const从右到左工作,第一个const通过这些指针的解引用禁止更改指向数组的int值(语句1),第二个const禁止更改指针本身(语句2)。

但我找不到如何使数组本身成为const,以便名为“array”的变量(在我看来是指向数组第一个元素的指针)不能更改为指向另一个第一个元素/数组(语句3)。

非常感谢您的帮助。谢谢。


4
std::array是C++标准库中的一个容器,它表示一个固定大小的数组。 - 463035818_is_not_a_number
1
C风格的数组在C++中使用时有一些特殊情况。std :: array修复了这些问题,使得C ++ std :: array具有更一致的行为,并且更接近其他C ++对象的行为。另一种选择是自己进行封装,例如struct Array2x2 { int array [2] [2]; };,这将使得这种2维数组作为参数和返回值更易于处理。 - Eljay
1个回答

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

衰变为:

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

可以使用const关键字:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接