Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

c++ - Memory management in allocating 2-D array

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
for(int i=0;i<n;i++)
{
    delete [] matrix[i];
}

delete [] matrix

You need to delete each of the internal arrays and then delete the array.

As has been suggested in a comment. A safer way of doing this would be to use standard containers such as std::vector. You could do something like this then:

std::vector<std::vector<int>> matrix;

This would give you a two dimensional array but you would not have to handle the cleanup.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...