【发布时间】:2017-04-05 01:29:29
【问题描述】:
我目前正在做一个需要 C 语言优先级队列的项目。我正在使用来自Rosettacode.org 的代码。
我正在尝试修改优先级队列,使其采用整数而不是字符。我尝试更改所有变量类型,但出现以下错误。
test.c:62:16: 警告:不兼容的整数到指针转换传递'int' 到 '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;
}
【问题讨论】:
-
不,显然您正在尝试修改队列,使其元素是整数而不是 string。因此,您应该将
char *更改为int,而不是将char更改为int。 -
push (heap_t *h, int priority, int *data)和push(h, 3, 3);--> 嗯。 3 不是指针。
标签: c pointers priority-queue function-call