如果我有一个二维指针数组并将其传递给函数:
int a = 5;
int* array[2][2];
array[0][0] = &a;
test(array);
我怎样才能定义这个函数,使得下面两个语句都不可能?
void test(int* array[2][2]) {
int b = 10;
// statement 1:
array[0][0] = &b;
// statement 2:
int* array2[2][2];
array = array2;
}
我试过这个:
void test(int* const array[2][2]) {
int b = 10;
// statement 1:
array[0][0] = &b; // is no longer possible
// statement 2:
int* array2[2][2];
array = array2; // is still possible
}
由于 const 从右到左工作,第一个 const 禁止更改指针(语句 1)。
但是我找不到如何使数组本身为const,所以名为“array”的变量,在我的理解中是指向数组第一个元素的指针,不能更改为指向另一个第一个元素/数组(语句 2)。
非常感谢帮助。谢谢。
void test(int const * const array[2][2])
衰减为:
void test(int const * const (* array)[2])
可以是常量:
void test(int const * const (* const array)[2])