[英]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 ++书籍,互联网等中找到答案。
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.