Home > front end >  g std=c 11 : is anything wrong in allocating/deallocating a 2d array this way
g std=c 11 : is anything wrong in allocating/deallocating a 2d array this way

Time:11-15

I'm using g -std=c 11 and this compact approach to allocate/deallocate 2d arrays :

int(*MyArray)[Ydim]=new int[Xdim][Ydim];
delete[] MyArray;

Everything seems to be working fine (compile time and run time). I know there are many ways to do the same but this is compact and seems to be doing the job. Is anything wrong with it?

Everything seems to work...but worried about subtle problems (memory leakage...)

Xdim and Ydim are compile time constants

CodePudding user response:

Assuming you want to stick to your current instantiation, I don't think you will receive any memory leak problems. If your internal nested array was a pointer as well you would need to de-allocate before de-allocating the external one.

Alternatives to avoid Dynamic Allocation:

To avoid the "new" and "delete" operators, and ease your worries about "subtle problems"

I would highly advise a swap to

std::vector<std::vector<int>> myArray(Xdim,std::vector<int>(Ydim,0));

I may even suggest you move to a flattened vector

std::vector<int> myArray = {Xdim * Ydim};

Better yet because your sizes are known at compile time in this case using std::array is preferential to vector.

std::array<std::array<int,Ydim>,Xdim> myArray = {};

or if you have the ability to use 3rd party libraries and specifically you are working with images I've found great success with OpenCV Matrices to represent 2 dimensional arrays.

  • Related