如何在 C++ 中删除这个二维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15037763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:55:13  来源:igfitidea点击:

How do I delete this 2D array in c++

c++pointersmemory-management

提问by Anubha

In simple 1D array:

在简单的一维数组中:

node *nodes =  new node[MAX_NODES];

Deleting by:

删除方式:

delete [] nodes;

Deletes all the nodes allocated in the array.

删除数组中分配的所有节点。

But in this case:

但在这种情况下:

float (*buildingArray)[3] = new float[10][3];

Does this statement make buildingArraya single dimension array of 3 float pointers? And this is the deallocation line:

此语句是否创建buildingArray了一个包含 3 个浮点指针的单维数组?这是释放线:

delete[] buildingArray;

Does the above deallocation deletethe array, but I am doubtful about whether it will delete its references?

上面是否释放delete了数组,但我怀疑它是否会删除其引用?

回答by Alok Save

Does the above de-allocation delete the array?

上述取消分配是否删除了数组?

Yes it does.

是的,它确实。

Simply follow the rule:

只需遵循以下规则:

You need to call deleteor delete []as many times you called newor new []respectively.

您需要调用deletedelete []多次调用newnew []



If you had an array of pointers where each index was allocated dynamic memory, you would need to explicitly loop through it and deallocate each array element explicitly.

如果您有一个指针数组,其中每个索引都分配了动态内存,则需要显式循环遍历它并显式释放每个数组元素。



On a side note you are much better off using a std::vectoror std::arrayrather than dynamically allocated array.

附带说明一下,您最好使用std::vectororstd::array而不是动态分配的数组。

回答by Qortex

Yes it does. The explanation is because there is no information in memory about how much dimensions your array has.

是的,它确实。解释是因为内存中没有关于数组有多少维的信息。

If you have a 3*4 items array, it's exactly the same as a 12 items array. It's just the way you address the specific elements (which are stored in a line after line fashion) that changes.

如果你有一个 3*4 items 的数组,它和一个 12 items 的数组完全一样。这只是您处理更改的特定元素(存储在一行一行的方式中)的方式。

So delete[]will work perfectly.

所以delete[]会完美地工作。

But using newand deleteoperators is not so common these days with smart pointers, unless you really have a good reason to control allocation yourself.

但是现在智能指针使用newdelete操作符并不常见,除非你真的有充分的理由自己控制分配。

回答by Mankarse

new float[10][3]allocates an array of 10 arrays of 3 floatsand returns a pointer to the first element (which is an array of 3 floats).

new float[10][3]分配一个包含 10 个 3 数组的数组,floats并返回一个指向第一个元素的指针(它是一个包含 3 个浮点数的数组)。

Calling delete[]on this pointer causes the whole array to be deleted.

调用delete[]这个指针会导致整个数组被删除。

The only difference between the two cases is that in the first case, the type of the values stored in the dynamically allocated array is floatand in the second case the type is float[3].

两种情况的唯一区别在于,在第一种情况下,动态分配数组中存储的值的类型是 ,float而在第二种情况下,类型是float[3]