简体   繁体   English

2D阵列动态数组上的运行时错误

[英]Run-time error on 2D array dynamic arrays

I have the following code: 我有以下代码:

int **arr = new int*[5];

for(int i = 0; i < 5; ++i)
    arr[i] = new int[];

for(int i = 0; i < 5; ++i)
    delete [] arr[i];

delete [] arr;

Now it compiles and runs successfully, however if I remove the array size '5' from the first line the code compiles but crashes with run-time error on the last line. 现在它编译并成功运行,但是如果我从第一行中删除数组大小'5',则代码编译但在最后一行崩溃并出现运行时错误。 I have the following questions that I have failed to find answers in Straustrup's C++ book, in the internet etc. 我有以下问题,我无法在Straustrup的C ++书籍,互联网等中找到答案。

  1. Why the code crashes in the specified case ? 为什么代码在指定的情况下崩溃? (My guess is that delete [] fails to find the array size to be deleted and crashes.) (我的猜测是delete []无法找到要删除和崩溃的数组大小。)
  2. If it is not allowed to allocate multidimensional arrays without indicating the size why such errors are not caught by compiler at compile time ? 如果不允许在不指示大小的情况下分配多维数组,为什么编译器在编译时没有捕获到这样的错误?

With the [5] , you're getting an array of 5 int* s. 使用[5] ,你得到一个5 int*的数组。

If you remove the [5] , you're saying you want a pointer to a pointer to an int . 如果你删除[5] ,你说你想要一个指向int的指针。 So essentially, you have new int*[1] . 基本上,你有new int*[1]

Then you are indexing it with numbers from 0 to 4, which is out of bounds. 然后你用0到4之间的数字索引它,这是超出界限的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM