المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : dynamic 2D array template for non-built-in types. [modified]



C++ Programming
04-03-2009, 04:55 PM
I'm building an Array2D template class to hold a custom class (I am testing with int to keep things simple)

Unfortunately I keep running into the same brick wall. I'll show some code first and then outline my problem.

Array2D.h
#pragma once
#ifndef INC_ARRAY_2D
#define INC_ARRAY_2D

typedef unsigned int UINT;

template
class Array2D
{
public:
Array2D(UINT TheWidth, UINT TheHeight)
{
Width = TheWidth;
Height = TheHeight;

ppArrayColumns = new T*[Width];
pArray = new T[Width*Height];

for(UINT i = 0; i < Width; i++)
{
ppArrayColumns = &pArray[i*Height];
}
}

Array2D(UINT Size);

~Array2D();

T* operator[] (UINT Index)
{
return ppArrayColumns[Index];
}

private:
T **ppArrayColumns;
T *pArray;

UINT Width;
UINT Height;
};

#endif

Array2D.cpp
#include "Array2D.h"

template
Array2D::Array2D(UINT Size)
{
Array2D(Size, Size);
}

template
Array2D::~Array2D()
{
delete[] *ppArrayColumns;
*ppArrayColumns = 0;
delete[] ppArrayColumns;
ppArrayColumns = 0;
pArray = 0; //No need to delete pArray, ppArrayColumns takes care of that for us.
}

ppArrayColumns is an array of pointers to type T, of size Width. pArray is an array of type T. The constructor for Array2D sets each element of ppArrayColumns to the address of the appropriate element of pArray. The end result [I]should allow us to access pArray like a regular 2D array, but it doesn't!

Each element of ppArrayColumns only points to one element of pArray. As such, when we use the [] operator, the whole thing falls apart because we've managed to walk into funny memory.

Is there any way I can make ppArrayColumns point to one element of pArray, yet still be able to access the next n elements (where n = Height)

Here is a diagram I have made for reference. (http://img4.imageshack.us/my.php?image=array2d.jpg)[^ (http://img4.imageshack.us/my.php?image=array2d.jpg)]

modified on Friday, April 3, 2009 8:46 AM