我目前正在做一个需要 C 优先级队列的项目。我使用的代码来自 Rosettacode.org .
我正在尝试修改优先级队列,使其采用整数而不是字符。我尝试更改所有变量类型,但出现以下错误。
test.c:62:16: warning: incompatible integer to pointer conversion passing 'int' to parameter of type 'int *' [-Wint-conversion]
当它是一个 char 时,它工作得很好,但当它是一个 int 时突然停止。为什么会这样?这是我的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int priority;
int *data;
} node_t;
typedef struct {
node_t *nodes;
int len;
int size;
} heap_t;
void push (heap_t *h, int priority, int *data) {
if (h->len + 1 >= h->size) {
h->size = h->size ? h->size * 2 : 4;
h->nodes = (node_t *)realloc(h->nodes, h->size * sizeof (node_t));
}
int i = h->len + 1;
int j = i / 2;
while (i > 1 && h->nodes[j].priority > priority) {
h->nodes[i] = h->nodes[j];
i = j;
j = j / 2;
}
h->nodes[i].priority = priority;
h->nodes[i].data = data;
h->len++;
}
int *pop (heap_t *h) {
int i, j, k;
if (!h->len) {
return NULL;
}
int *data = h->nodes[1].data;
h->nodes[1] = h->nodes[h->len];
h->len--;
i = 1;
while (1) {
k = i;
j = 2 * i;
if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
k = j;
}
if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
k = j + 1;
}
if (k == i) {
break;
}
h->nodes[i] = h->nodes[k];
i = k;
}
h->nodes[i] = h->nodes[h->len + 1];
return data;
}
int main () {
heap_t *h = (heap_t *)calloc(1, sizeof (heap_t));
push(h, 3, 3);
push(h, 4, 4);
push(h, 5, 5);
push(h, 1, 1);
push(h, 2, 2);
int i;
for (i = 0; i < 5; i++) {
printf("%d\n", pop(h));
}
return 0;
}
最佳答案
在您的 push()
函数签名中,第三个参数的类型为 int *
,但您在调用时发送了一个 int
它。指向整数转换的指针是一种特定于实现的行为,很可能导致 undefined behavior .
在我看来,您不需要将 data
作为指针,一个简单的 int
就可以了。
关于c - C 中的优先级队列实现 - 将字符更改为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43213688/