首页 > 解决方案 > “二维数组”的常量自动变量允许在常量二维数组中修改值吗?

问题描述

所以我为此使用了视觉工作室。我正在摆弄创建数组并意识到作为数组的 const auto 变量允许出于某种原因更改数组值?然后我也尝试了一个 const 指针数组,它当然会导致错误。

我将两个数组都初始化为全 0。但是,如果我更改 const auto 数组中索引处的任何值,它不会引发错误。我还没有在任何其他框架作品上测试过这个。

int main()
{
    const int x = 5;
    const int y = 4;

    const auto arr = new int[x][y] (); //Sets arr to all 0's

    int a = 3; //variable to be inserted

    arr[0][0] = a; //Allows for change at index
    arr[3][2] = a; //Allows for change at index

    for (int i = 0; i < x; ++i)
    {
      for (int j = 0; j < y; ++j)
      {
         cout << arr[i][j] << " "; //Prints arr
      }         
      cout << endl;
    }

    //Now on to pointer array
    const int *pt = new int[x * y] (); //Sets pt to all 0's

    for (int i = 0; i < x; ++i)
    {
      for (int j = 0; j < y; ++j)
      {
        pt[i * y + j] = a; //Obliviously Throws modifiable error 
        cout << pt[i * y + j] << " "; 
      }
      cout << endl;
    }
}

第一个数组这样打印(const auto array):

3 0 0 0

0 0 0 0

0 0 0 0

0 0 3 0

0 0 0 0

如上所述,第二个数组引发错误。

标签: c++arrayspointersinitializationauto

解决方案


推荐阅读