英文:
How to pass a two-dimensional array of pointers as const?
问题
I'll provide the translation of the code and your question:
如果我创建一个指针的二维数组并将其传递给一个函数:
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禁止通过解引用更改指针数组的指针指向的int值(语句1),第二个const禁止更改指针本身(语句2)。
但我无法找到如何使数组本身成为const,以便我的理解中名为"array"的变量无法更改为指向另一个首元素/数组(语句3)。
非常感谢您的帮助。谢谢。
英文:
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.
答案1
得分: 4
void test(int const * const (* array)[2])
英文:
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])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论