Thursday 14 March 2013

Dynamic 2D Integer Array

I would like to share my experience on implementing the square brakets ([ ]) operator overloading method in the dynamic 2D integer array class, IntArrArr.

Here is the IntArrArr class header file:
class IntArrArr{
  IntArr** _data;
  unsigned int _size;
  unsigned int _width;
  public:
    IntArrArr(unsigned int size,unsigned int width);
    IntArr& operator[](unsigned int index);
    unsigned int Size()const;
    virtual ~IntArrArr();
}; 
IntArr is a dynamic 1D integer array class implemented during week 5 of my OOP344 class. The original implementation for IntArrArr was also done in class, which had index loop back for the operator overload method.

Below is the implementation for the operater overload method that resizes the array when the index given is greater than the array size:
  IntArr& operator[](unsigned int index){
        IntArr** temp;
        if (index >= _size){
            int i;

            //Step 1: Make a temporary array with a new size
            unsigned int newsize = index < 1024? index*2 : index + 1024;
            temp = new IntArr* [newsize];

            //Step 2: Null each element of the temporary array
            for (i = 0; i < (int)newsize; i++){
                temp[i] = 0;
            }

            //Step 3: Copy data from the old array to the temporary array 
            for (i = 0; i < _size; i++){
                temp[i] = _data[i];
            }
            //Step 4: Add a new array to the next avaliable index
            temp[i] = new IntArr(_width);

            //Step 5: Delete the old array
            delete [] _data;

            //Step 6: Update the size and data pointer 
            _size = newsize;
            _data = temp;
        }
        else if(_data[index] == 0){
            _data[index] = new IntArr(_width);
        }
        return *_data[index];
    }

I struggled with step 5 of the implementation. Previously, I deleted each of the elements in the old array using a for loop. The reason why deleting each element of the old array does not work is because shallow copying  was used to copy elements from the old array to the new array in step 3. Deleting each element in the old array would mean deleting the elements in the temporary array as well. So when I tried accessing the array, I got a runtime error for accessing an IntArr object that does not exist.

Special thanks to my OOP344 group members in iCODE for showing me the proper way to implement the CDialog add function.

For those interested in viewing the full implmentation of IntArrArr, it is in my github repository.


No comments:

Post a Comment