简体   繁体   中英

Deallocate multidimensional array in c++

How would I go about destroying a dynamic array of arbitrary size, dimensions, and type? Will delete[] automatically go down the levels of a two dimensional array or just delete the first level of pointers so the program need to manually iterate over each array level?

Ideally I need a single command (for use in a template class) that will destroy one to four dimensional arrays. It would also work if there is a way to check the number of dimensions of an array.

I am using dymanic arrays such as double* ar = new double[100];

如果您使用的是C ++,请使用std::vectorstd::unique_ptr

You need to manually iterate over all levels to delete them.
If there is a way to check the dimensions, you can just use that to select the correct destruction process.

Also, why not use vectors ? they are fast and are automatically deallocated when out of scope

if you instanciate the 2 dimensional array like new int[10][20] the delete[] will destroy all the array, but if you created it iterating like myarray[i] = new int[20] so you will have to iterate again to destroy each dimension.

If you are not sure about how to destroy the array I would recoment you to use the STL vector.

Basically 1 new = 1 delete and 10 new = 10 delete , so you have to delete everything you allocate, the number of those operation called should be equal.

There's no way of knowing (from compilers/programs point of view) what's the real data pointer, what's just some trash or what is referenced elsewhere (and will be used) and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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