Consider the following way of working with a dynamically allocated two-dimensional array (for some reason, this way does not appear among the replies here):
const int nRows = 2, nCols = 3;
int (*arr)[nCols] = (int(*)[nCols])(new int[nRows * nCols]);
arr[1][1] = 2;
std::cout << arr[1][1] << endl;
delete[] arr;
Does delete[] in the last line free the memory correctly in this case?
This is undefined behaviour; the type of the argument to delete must have the same type as the result of the corresponding new.
You could improve the code with:
int (*arr)[nCols] = new int[nRows][nCols];
(or even auto *arr = ...) in which case the same delete expression would be correct. Having to use a cast is generally a sign you've taken a mis-step.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With