Memory management in allocating 2-D array

后端 未结 2 1036
耶瑟儿~
耶瑟儿~ 2020-12-22 04:21

I have allocated a two dimensional array using the following code:

// Dynamic allocation
        int **matrix=new int*[n];
        for(int i=0;i

        
相关标签:
2条回答
  • 2020-12-22 04:32
    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.

    0 讨论(0)
  • 2020-12-22 04:37

    "What is the correct way of doing it?"

    Using standard containers like e.g. std::vector<std::vector<int>> or std::array<std::array<int,N>,N> (supposed N is already known at compile time) is the correct way.
    You don't use new()/new[] and delete/delete[] in 1st place (besides rare valid use cases).

    If you're sure you have such case, you delete in exactly the reverse order as you were allocating using new[]. delete [][]; isn't valid syntax, as the compiler already told you.

    0 讨论(0)
提交回复
热议问题