You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将二维指针数组以const形式传递以禁止三类修改操作?

解决方案

要同时禁止三类语句的执行,关键在于理解函数参数中数组的退化规则:当你将二维指针数组int* array[2][2]传递给函数时,它会退化为指向一维数组的指针(即int* (*array)[2]),而非二维指针。要实现三重限制,需要从三个维度添加const修饰:

  • 禁止通过指针解引用修改指向的int值(语句1):让指针指向const int
  • 禁止修改数组内的指针元素(语句2):让数组元素成为const指针
  • 禁止修改函数参数array本身(语句3):让指向数组的指针成为const指针

正确的函数定义写法

直接使用指针语法的完整写法:

void test(int const * const (* const array)[2])
{
    int c = 20;

    // statement 1: 编译错误,无法修改const int
    *(array[0][0]) = c;

    // statement 2: 编译错误,无法修改const指针
    array[1][1] = &c;

    // statement 3: 编译错误,无法修改const指针(array本身)
    int* array2[2][2];
    array = array2;
}

如果觉得语法过于复杂,可以用typedef简化可读性:

// 定义一个包含2个const指针的数组类型,指针指向const int
typedef int const * const ConstIntPtrArr[2];

void test(const ConstIntPtrArr * const array)
{
    int c = 20;

    // 三类语句均会触发编译错误
    *(array[0][0]) = c;
    array[1][1] = &c;
    ConstIntPtrArr array2;
    array = &array2;
}

原有写法无法禁止语句3的原因

你之前的int const * const array[2][2]作为函数参数时,会被编译器解析为int const * const (*array)[2]——这里的array是一个可修改的指针(指向包含2个const指针的数组),因此你可以给它重新赋值另一个数组的地址。只有在这个指针前添加const(即int const * const (* const array)[2]),才能禁止修改array本身的指向。

内容的提问来源于stack exchange,提问作者VincentSchaerl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 01:32:38