tags:

views:

142

answers:

4

Suppose you have an array, items, with capacity 5 and suppose also you have a count varaible that counts each entry added to the array. How would you realloacte the array? Using C++ syntax?

void BST::reallocate()
{
    item *new_array = new item[size*2]; 
 for ( int array_index = 0; array_index < size * 2; array_index++ ) 
    {
        if ( ! items[array_index].empty )
        {
   new_array[array_index].theData = items[array_index].theData;
   new_array[array_index].empty = false;
  }
    }
    maxSize += size;
    delete [] items;

    items = NULL;
    items = new_array;
 }

How do you reallocate an array? BST ctor is below with the private items struct, just to eliminate any confusion.

BST::BST(int capacity) : items(new item[capacity]), Position(0), 
leftChild(0), rightChild(0), maxSize(capacity)
{

}

this is in the BST header:

private:
 int size;
 int maxSize;
 int Position;
 int leftChild;
 int rightChild;
 struct item
 {
  bool empty;
  data    theData;

 };

 item *items;

The quesetion is that i seem to be having a hard time with the reallocation of my items array.

+3  A: 

Your old array items has only size elements, so you need to change the upper limit in your for loop to size from size*2 when you're copying the old elements to the new array.

jk
+8  A: 

I would reallocate it in the form of a std::vector<item>, assuming that there is no overriding reason to use an array. That would avoid several problems completely.

David Thornley
+6  A: 

Why are you doing this at all? Why do you think that:

std::vector<item> items;

won't work for you?

Jerry Coffin
I think this is homework although not tagged as such.
BostonLogan
+1  A: 

May be coz size is not initialized. Also, you would need to make sure size is < maxSize.

VNarasimhaM