英文:
How to pass a two-dimensional array of pointers as const?
问题
I can provide the translated code without the programming-related content:
如果我创建一个二维指针数组并将其传递给一个函数:
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;
// 语句 1:
*(array[0][0]) = c;
// 语句 2:
array[1][1] = &c;
// 语句 3:
int* array2[2][2];
array = array2;
}
我尝试过这样:
void test(int const * const array[2][2])
{
int c = 20;
// 语句 1:
*(array[0][0]) = c; // 不再可能
// 语句 2:
array[1][1] = &c; // 不再可能
// 语句 3:
int* array2[2][2];
array = array2; // 仍然可能
}
由于const从右到左工作,第一个const禁止通过这些指针的解引用来更改数组指针指向的整数值(语句1),第二个const禁止更改指针本身(语句2)。
但我无法找出如何使数组本身成为常量,以便不能更改名为“array”的变量,这在我理解中是指向数组的第一个元素的指针,不能更改为指向另一个第一个元素/数组(语句3)。
非常感谢您的帮助。谢谢。
<details>
<summary>英文:</summary>
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.
</details>
# 答案1
**得分**: 4
void test(int const * const (* array)[2]) decays to: void test(int const * const (* const array)[2])
<details>
<summary>英文:</summary>
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])
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论