【发布时间】:2020-04-08 21:03:07
【问题描述】:
我正在尝试创建一个函数来创建优先级队列。我的结构是这样的:
struct node {
char *item;
struct node *next;
};
struct queue {
struct node *start;
struct node *end;
};
struct priority_queue {
struct queue **aoq;
int x;
};
我要实现的功能是:
struct priority_queue *priority_queue_create(int x);
这里,从结构priority_queue中可以看出,struct queue **aoq本质上是一个队列数组,这是我想要的。 int x,在函数头中,是数组中的队列数。
我的看法是这样的:
struct priority_queue *priority_queue_create(int x) {
struct priority_queue *pq = malloc(sizeof(struct priority_queue));
pq->x = x;
pq->aoq = malloc(x* sizeof(struct queue));
return pq;
}
我在上面的代码中放置 3 行注释的地方是我怀疑我的错误所在的地方。我希望能够执行以下操作:如果 x = 3,则应该有一个包含 3 个队列的数组,并且我想我可以通过执行类似
的操作来访问它pq->aoq[0] /// to access the first queue in the array, or
pq->aoq[2] /// to access the third queue in the array
谁能帮助我修复我的实现?提前致谢。
编辑: 我尝试过的其他实现:
struct priority_queue *priority_queue_create(int x) {
struct priority_queue *pq = malloc(sizeof(struct priority_queue *));
pq->x = x;
pq->aoq = malloc(x * sizeof(struct queue *));
for (int i = 0; i < x; ++i) {
pq->aoq[i] = malloc(sizeof(struct queue));
}
return pq;
}
【问题讨论】:
-
对不起,他们是错别字。我在上面编辑过。
-
malloc(x * sizeof(struct queue))应该是malloc(x * sizeof(struct queue *)) -
那么你需要为每个
struct queue节点分配内存并分配给pq->aoq[i]。 -
我刚试过。它不适合我。
-
“它不工作”并没有告诉我们问题是什么。更新问题中的代码并清楚地描述“不工作”的含义。