简体   繁体   中英

Pointer to Pointer to Structure (Priority Queue)

I'm a beginner (in C++, I'm coming from C (6 months experience)) and I'm trying to create a priority queue, but something is not working. When I start the program and compile it, there are no errors. But there is nothing printed on the screen and the program crashes.

So here is the code:

PriorityQueue.h

using namespace std;

class PriorityQueue{
    private:
    struct pqentry_t{
        string value;
        float priority;
    };
    pqentry_t **_pqentry;
    int _size;
    int _next;

    public:
    PriorityQueue();
    ~PriorityQueue();
    void insert(string value, float priority);
    void printQueue();
};

PriorityQueue.cpp

#include <iostream>
#include <string>
#include "PriorityQueue.h"

#define SIZE 8
using namespace std;

PriorityQueue::PriorityQueue(){
    _size = SIZE;
    _next = 0;
    _pqentry = new pqentry_t*[_size];
}

PriorityQueue::~PriorityQueue(){
    delete[] _pqentry;
}

void PriorityQueue::insert(string value, float priority){
    _pqentry[_next]->value = value;    // this is probably not working
    _pqentry[_next]->priority = priority;
    _next++;
}

void PriorityQueue::printQueue(){
    for (int i = 0; i < _next; i++){
            cout << "Value: " << _pqentry[i]->value << endl
                 << "Priority: " << _pqentry[i]->priority << endl;
        }
        cout << endl;
}

main.cpp

#include <iostream>
#include <string>
#include "PriorityQueue.h"

using namespace std;

int main()
{
    PriorityQueue pq;
    pq.insert("Banana", 23);
    pq.printQueue();
}

I think, I know where the error is, in the PriorityQueue.cpp, here:

_pqentry[_next]->value = value;
_pqentry[_next]->priority = priority;

But I don't know what's wrong and I can't fix it. The compiler says there are no errors.

I hope, you can help me. Thanks in advance!

You did allocate the _pqentry member but you need to allocate each entry of this array as well, for example:

_pqentry[_next] = new pqentry_t;

before writing to it. And do not forget to delete those :)

It looks like you are creating an array of pointers to pqentry_t in your constructor, but your insert method is expecting it to be an array of _pqentry structures themselves. You are not allocating space for the pqentry_t elements themselves and so when you try to dereference them in your insert method, the program crashes.

Try changing the definition of _pqentry in the class to pqentry_t *_pqentry and the allocation in the constructor to new pqentry_t[size]. This will allow your insert and printQueue methods to access the entries of _pqentry as they are written.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM