Pergunta

I am trying to resize a heap object so that the program can continue if the user tries to build a heap that exceeds heap capacity. I am able to return a pointer that points to the new heap, but this does not work well with the other parts of my program. I would like to directly change where my pointer p points to. Here is my attempt to do so. It compiles but the pointer still points to the old location. Please help me fix this code so that I don't have to return a pointer from my BuildHeap function. I would post all of my code, but this is homework and I would not want my work copied.

HEAP* Initialize(int n) {
    HEAP* p;
    p = new HEAP;
    p->size = 0;
    p->capacity = n; 
    p->H = new ELEMENT[p->capacity+1]; //first address not used, so we need +1 here
    return p;
}

void Resize(int n, HEAP*& ptr) { //pass pointer by reference
    ptr = Initialize(n);
}

void BuildHeap(HEAP* p, ELEMENT *A) {
    int length = A[0].key;      //length = array size stored in A[0]
    if(length <= p->capacity) {
        p->size = length;
        for(int i = 1; i <= length; i++) {
            p->H[i].key = A[i].key; //copy ELEMENT array into heap object's H array
        }
        for(int i = (length) / 2; i >= 1; i--) 
            MaxHeapify(p, i);
    }
    else {
        cout << "Error: Heap capacity exceeded. Resizing heap.\n";
        Resize(length, p); //initialize a new, larger heap
        BuildHeap(p, A);
        cout << "Heap built with new heap capacity of " << p->capacity << ".\n";
    }
}

Edit: I was able to resolve my issue by checking if the pointer needed to be changed before even calling BuildHeap:

if(length > p->capacity) { //resize heap if capacity is exceeded
    cout << "Error: Heap capacity exceeded. Resizing heap.\n";
    p = Initialize(length);
}
BuildHeap(p, A);
Foi útil?

Solução

I think your problem is that you are only using a reference to the pointer in one place, but not in others. Look at the signature of BuildHeap:

void BuildHeap(HEAP* p, ELEMENT *A)

Here, when you call BuildHeap, a copy of the pointer passed as the first argument p is made. Your subsequent call to Resize modifies that copy, but the caller of BuildHeap still has its own, unmodified pointer. You might want to change the signature of BuildHeap (and possibly other methods) to use references as well:

void BuildHeap(HEAP*& p, ELEMENT *A)

That said, you might want to consider using a class where you use a pointer which is a member variable so you don't have to pass it around all the time manually.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top