In article <38********************@twister1.libero.it>,
dade <ce****@libero.itwrote:
Hi,
i use a dynamic 3D matrix of structure that yields to a 90Mb of RAM
allocated.
To do that i use new operator. here a portion of code
struct SInfo
{
int i1;
int i2;
float f1;
float f2;
}
SInfo ***pCoord = new SInfo **[iELM_MAT_R];
for(j=0; j<iELM_MAT_R; j++)
{
pCoord[j] = new SInfo *[iELM_MAT_C];
for(k=0; k<iELM_MAT_C; k++)
{
pCoord[j][k] = new SInfo[MAX_ELM];
}
}
Better would be a class:
template < typename T >
class Array3D
{
public:
Array3D( unsigned x, unsigned y, unsigned z ):
l( x ), h( y ), w( z ), rep( x * y * z ) { }
T& at( unsigned x, unsigned y, unsigned z ) {
assert( x < l && y < h && z < w );
return rep[ x * l * h + y * h + z ];
}
const T& at( unsigned x, unsigned y, unsigned z ) const {
assert( x < l && y < h && z < w );
return rep[ x * l * h + y * h + z ];
}
private:
unsigned l, unsigned h, unsigned w
std::deque< T rep;
};
(Someone double check me on the above, I didn't test it.)
and it works...but i read that it is better to use malloc and free
instead of new and delete to avoid memory leaks.
That's silly.
i don't see error in my code but i'd like to know if there is something
i'm skipping...
You should use const unsigned for your array bounds rather than defines,
you need to remember to delete all the memory you newed, and the code
you have above needs to be made exception safe.
Use a class like the one I have above instead. It is a complete solution
in fewer lines of code, easer to maintain and more likely to be correct.
--
To send me email, put "sheltie" in the subject.