[Subject Prev][Subject Next][Thread Prev][Thread Next][Subject Index][Thread Index]

RE: c++: 2D array



hi all,
	thanks to vikram,james ,sourya, and sridhar. I have made a small
2D array class based on suggestions of u all. I have overloaded the []
operator to return a pointer which itself points to an array as described
by james.
	I have also used a destructor to remove the memory on heap. Here's
the code. Could you comment on ways of bettering this especially the array
bounds check.(although which are not checked by an array in general).
<code>

#include<iostream.h>
class twoDArray
{
	private:		
	int rows;
	int cols;

	public:

	double **element;

	twoDArray(int rows, int cols)
	{
		element = new double * [rows];
		element[0] = new double[rows*cols];
		for(int i=1;i<rows;i++)
			element[i] = element[i-1] + cols;
			
	}
	~twoDArray()
	{
		delete [] element[0];
		delete [] element;
	}

	double *operator [](int i)
	{
		return this->element[i];
	}
	
	int getRows(){return rows;}
	int getCols(){return cols;}
};

main()
{
	twoDArray t(2,3);
	cout<<t[1][2];
	t[1][2]=12;
	cout<<t[1][2];
}

</code>
On Thu, 21 Sep 2000, Sarcar, Shourya (MED) wrote:

> the memcpy feature is cool but beware, if you delete ptr, you have the
> problem of dangling pointers with ptr[1,2,3,4]
> but anyway, i like the recursive structure :)
> 

-- 

#!!!	If anything can go wrong, _FIX_ it. (To hell with MURPHY)
	
						Ajay kumar Dwivedi
						 ajayd@xxxxxxxxxx