指针指向结构的指针(优先队列)

Pointer to Pointer to Structure (Priority Queue)

本文关键字:指针 优先队列 结构      更新时间:2023-10-16

我是初学者(在C 中,我来自C(6个月的经验)),我正在尝试创建优先队列,但某些事情不起作用。当我启动程序并进行编译时,没有错误。但是屏幕上没有打印任何东西,并且程序崩溃了。

所以这是代码:

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();
}

我想,我知道错误在哪里,在Priorityqueue.cpp中,此处:

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

但是我不知道怎么了,我无法修复它。编译器说没有错误。

我希望,您可以帮助我。预先感谢!

您确实分配了_pqentry成员,但是您还需要分配此数组的每个条目,例如:

_pqentry [_next] = new Pqentry_t;

写信之前。并且不要忘记删除这些:)

看起来您正在为构造函数中的pqentry_t创建一系列指针,但是您的插入方法期望它本身就是_pqentry结构的数组。您不是在为pqentry_t元素分配空间本身,因此,当您尝试在插入方法中解释它们时,程序会崩溃。

尝试将类中_pqentry的定义更改为pqentry_t *_pqentry,以及构造函数中的分配到新的pqentry_t [size]。这将允许您的插入和printqueue方法访问_pqentry的条目。