Topic: How to dynamically create 2-d array of Objects???
Author: robert@puente.Jpl.Nasa.Gov
Date: Sat, 1 May 1993 00:22:57 GMT Raw View
C++ gurus,
I want to do the following and have been failing miseribally:
class A{};
main(void)
{
A* tmp; // I know this isn't correct...
//read M and N.
tmp = new A[M][N];
}
I then tried the following:
A* tmp;
tmp = new *A[M];
for( i = 0; ... )
tmp[i] = new A[N];
Any help is appreciated. Thanks
-r
Author: andy@cerl.gatech.edu (Andy Register)
Date: 1 May 1993 14:21:36 GMT Raw View
In article <1993May1.002257.12281@llyene.jpl.nasa.gov> robert@puente.Jpl.Nasa.Gov writes:
>C++ gurus,
> I want to do the following and have been failing miseribally:
>
>class A{};
>
>main(void)
>{
> A* tmp; // I know this isn't correct...
>
> //read M and N.
>
> tmp = new A[M][N];
>}
>
>I then tried the following:
>
>A* tmp;
>
>tmp = new *A[M];
>
>for( i = 0; ... )
> tmp[i] = new A[N];
>
>
>Any help is appreciated. Thanks
>
>-r
Here is some code from a 2-D Matrix template I have coded. The
class is called GTMatrixRep and I have included the default ctor
and the dtor. You can look at this code to figure out how to
construct a 2-D array and how to destroy it.
This topic needs to be added to the FAQ if it is not already.
(It has been a long time since I re-read the FAQ)
The entire matrix hierarchy is available for ftp but it is still
in testing and there is scant documentation. If you want to use
it and help debug, I can provide you more info on how to get
it. I have used it and it seems pretty stable but it needs testing
before I release it into public domain.
Anyway, here are the constructors and destructors.
template <class T>
void GTMatrixRep<T>::CtorHelper(int RowSize, int ColSize) {
num_rows = RowSize;
num_cols = ColSize;
mel = new T* [num_rows];
for (int row = 0 ; row < num_rows ; row++)
mel[row] = new T[num_cols];
// zero all elements
// This is a problem.
// Here is the problem:
// T DefaultValue; // calls default ctor.
// double DefaultValue; // not a nice number.
// Leaves two choices:
// one is to do T DefaultValue(0) which inits
// intrinisic types to zero but requires a T ctor
// with int, double, etc. But you want a default.
// two is to do T DefaultValue() which gives default
// (which is undefined for intrinsic types.
// (sigh!)
T DefaultValue = 0;
for (row = 0 ; row < num_rows ; row++)
for (int col = 0 ; col < num_cols ; col++)
mel[row][col] = DefaultValue;
}
template <class T>
void GTMatrixRep<T>::DtorHelper(void) {
for (int row = 0 ; row < num_rows ; row++)
delete [] mel[row];
delete [] mel;
num_rows = 0;
num_cols = 0;
}
template <class T>
GTMatrixRep<T>::GTMatrixRep(int RowSize, int ColSize) {
// trap negative sizes
if (RowSize < 0 || ColSize < 0) {
cerr << msg[3] << endl;
exit(0);
}
CtorHelper(RowSize, ColSize);
}
template <class T>
GTMatrixRep<T>::~GTMatrixRep(void) {
DtorHelper();
}
Toodles
Andy