CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: deallocate matrix

  1. #1
    Join Date
    May 2018

    deallocate matrix

    I'm not sure to follow right procedure to deallocate this 2 dimensional array from heap memory.
    Is't right "~Distributore" method?

    #include <iostream>
    using namespace std;
    const int P=5;    // n. pezzi max per slot
    const int S=5;    // n. di slot
    class Distributore {
            int** armadio;
            int ripiani;
            Distributore(const int);
            bool acquista(int);
            bool aggiungi(int,int);
            friend ostream& operator<<(ostream&, const Distributore&);
            Distributore(const Distributore&);
            Distributore operator+(int);
    Distributore::Distributore(const int num)           //costruttore
        for(int r=0; r<ripiani; r++)
            armadio[r]=new int[S];
        for(int r=0; r<ripiani; r++)
            for(int c=0; c<S; c++)
    Distributore::~Distributore() //distruttore di copia
        for (int i=0; i<ripiani; i++) {
            delete[] armadio[i];
        delete[] armadio;
    Last edited by 2kaud; May 24th, 2018 at 03:12 AM. Reason: Added code tags

  2. #2
    Join Date
    Feb 2017

    Re: deallocate matrix

    Quote Originally Posted by zio_mangrovia View Post
    I'm not sure to follow right procedure to deallocate this 2 dimensional array from heap memory.
    It looks correct to me. You first delete all row arrays (the ripianis) and then finally the column array (the armadio). But then again I haven't deleted anything for years.

    I would instead base the matrix on std::vector. It's a dynamic array (so you can determine the size at runtime), and it has the big advantage of automatically deleting itself when it's no longer in use (when it goes out of scope).

  3. #3
    Join Date
    May 2018

    Re: deallocate matrix

    thanks, these exercises are for exams about heap and vectors

  4. #4
    Join Date
    Nov 2003

    Re: deallocate matrix

    Your implementation looks correct.
    I know this is for an exam, so you don't have a choice, but in other circumstances, you should use something like an std::vector of std::vectors as wolle mentioned.
    Basically, the rule of modern C++ is to never use raw pointers when ownership is involved.
    Marc Gregoire - NuonSoft (http://www.nuonsoft.com)
    My Blog
    Wallpaper Cycler

    Author of Professional C++, 4th Edition by Wiley/Wrox (includes C++17 features)
    ISBN: 978-1-119-42130-6
    [ http://www.facebook.com/professionalcpp ]

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)