-
May 24th, 2018, 12:24 AM
#1
deallocate matrix
I'm not sure to follow right procedure to deallocate this 2 dimensional array from heap memory.
Is't right "~Distributore" method?
Code:
#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;
public:
Distributore(const int);
bool acquista(int);
bool aggiungi(int,int);
friend ostream& operator<<(ostream&, const Distributore&);
Distributore(const Distributore&);
Distributore operator+(int);
~Distributore();
};
Distributore::Distributore(const int num) //costruttore
{
ripiani=num;
armadio=new(int*[ripiani]);
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++)
armadio[r][c]=1;
}
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
-
May 24th, 2018, 01:18 AM
#2
Re: deallocate matrix
Originally Posted by zio_mangrovia
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).
-
May 26th, 2018, 12:07 AM
#3
Re: deallocate matrix
thanks, these exercises are for exams about heap and vectors
-
June 2nd, 2018, 09:00 PM
#4
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|