Originally Posted by
grumpy
This decision is one of the most common mistakes by newbies. It offers the opportunity for the user of your class to forget to initialise it (i.e. create the array), and then to use it despite not having initialised it.
For the purposes of my program, I require several 3D (and 6D) arrays to be globally accessible from a specific class, but I don't know what it's dimensions are until runtime. Once allocated I don't need to change their size (which is why I was suggesting that vectors might be overkill). So I need to declare them in the header of the class before I can allocate them. The two main cricisisms I've seen in your replies is:
- no bounds checking
- danger of using array before allocated
I've come up with the following class where you allocate using:
image.allocate(100,100,100);
and get and put values using
cout<<image.put(23,22,13,0.2);
cout<<image.get(23,22,13);
Once whatever code I am writign is tested and I know there are no out of bounds problems I can always substitute for a similar class without the bounds checking and see if I gain in performance.
Code:
#include <iostream>
using namespace std;
class array3d
{
public:
void allocate(int nx,int ny,int nz);
double get(int i,int j,int k);
int put(int i,int j,int k,double value);
array3d();
~array3d();
private:
double ***array; // The pointer to the array
int nx,ny,nz; // The dimensions of the array
int allocated; // Whether the array has been allocated
};
/* CONSTRUCTOR */
array3d::array3d() {
allocated=0;
}
/* ALLOCATION FUNCTION */
void array3d::allocate(int a,int b,int c) {
if(!allocated) {
allocated=1;
nx=a;
ny=b;
nz=c;
array = new double**[nx];
for(int i=0;i<nx;i++)
{
array[i] = new double*[ny];
for(int j=0;j<ny;j++)
{
array[i][j] = new double[nz];
}
}
} else {
cout<<"ERROR: array already allocated"<<endl;
abort();
}
}
/* DESTRUCTOR */
array3d::~array3d() {
for(int i=0;i<nx;i++) {
for(int j=0;j<ny;j++) {
delete []array[i][j];
}
delete []array[i];
}
delete []array;
}
/* GET VALUE */
double array3d::get(int i,int j,int k) {
if(allocated) {
if(i>=0 && i<=nx && j>=0 && j<=ny && k>=0 && k<=nz)
{
return array[i][j][k];
}
cout<<"ERROR: indices out of bounds"<<endl;
abort();
}
cout<<"ERROR: array not allocated"<<endl;
abort();
}
/* PUT VALUE */
int array3d::put(int i,int j,int k,double value) {
if(allocated) {
if(i>=0 && i<=nx && j>=0 && j<=ny && k>=0 && k<=nz)
{
array[i][j][k] = value;
return 0;
}
cout<<"ERROR: indices out of bounds"<<endl;
abort();
}
cout<<"ERROR: array not allocated"<<endl;
abort();
}
Would the above be considered bad coding, or does it seem like a sensible approach to my problem?
Thanks!