如何将指向二维指针数组的参数传递为const?

huangapple go评论102阅读模式
英文:

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] = &amp;a;
array[1][1] = &amp;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] = &amp;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] = &amp;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&#39;t find out how to make the array itself const, so that the variable named &quot;array&quot;, which in my understanding is a pointer to the first element of the array, can&#39;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>



huangapple
  • 本文由 发表于 2023年3月21日 01:53:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75793690-3.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定