“二维数组”的常量自动变量是否允许在常量二维数组中修改值?

时间:2019-05-30 05:12:33

标签: c++ arrays pointers initialization auto

所以我正在为此使用Visual Studio。我在摆弄数组,并意识到作为数组的const自动变量由于某种原因而允许更改数组值?然后我也用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

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

0 个答案:

没有答案
相关问题