I have allocated a two dimensional array using the following code:
// Dynamic allocation
int **matrix=new int*[n];
for(int i=0;i<n;i++)
{
matrix[i]=new int[n];
}
This works fine.
- Firstly we allocate an array of integer pointers.
- Then we further allocate each of the earlier pointer to point at a memory location of
n
integers. This creates our two dimensional array.
I know that a destructor for a dynamically allocated array should look like:
~SquareMatrix()
{
delete [] OneDarray;
}
The emphasis being on []
because if it is not written, only the first element of the array will be deleted.
On similar grounds, I guess I need to place the []
twice so as to delete the entire two dimensional array, like,
delete [] [] matrix;
But this is not working and giving a compile time error.
What is the correct way of doing it?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…