0

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
  • The problem is that it is crashing Commented Nov 19, 2009 at 20:02
  • its crashing on assignment from items[i].theData to new_array[i].theData. Commented Nov 19, 2009 at 20:07
  • Aside: items = NULL is unnecessary, since you reassign items immediately afterwords. Commented Nov 19, 2009 at 20:30

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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

std::vector<item> items;

won't work for you?

Comments

3

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.

Comments

1

Maybe because size is not initialized. Also, you would need to make sure size is less than maxSize.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.