They are not similar. The obvious reason why they are not similar is that you're calling new[]
6 times, and in the second version of delete[]
, you're calling "delete" 2 times.
delete [] *M;
delete [] M;
For every call to new[]
, you're supposed to match it with delete[]
, and obviously you are not doing that.
If you want those two calls to delete[]
to match, you must change the way you allocated the 2d array. The change would be this:
int** M = new int*[5];
int *pool = new int[5*3];
for (int i = 0; i < 5; ++i, pool += 3)
M[i] = pool;
In the example above, only 2 calls to new[]
are made, once for the row pointers, and a second one for the memory pool. Then the loop just points each row pointer inside the pool in the proper place.
Now, the "2 call" delete[]
will work correctly, providing you don't do anything strange such as corrupt memory between the time you allocated and deallocated the array.
The advantage of allocating 2d arrays this way is that new[]
is called only twice, regardless of the number of columns. So if you had a 10,000 x 10,000 matrix, your original version would need to call new[]
10,001 times, while the version above that uses the pool would need only 2 calls to new[]
. This would more than likely speed up the program, since the allocator is only called twice (and then twice more for deallocation).
In addition, the method above is preferred if the array data needs to be contiguous, so that simple pointer arithmetic can be used to go to any row or column.
However, make sure that:
- your array does not change size and
- it is not ragged (all rows must have the same number of columns).
Otherwise it becomes more difficult to maintain a matrix that is allocated in the way I described.