Search code examples
cpointerspriority-queuefunction-call

priority queue implementation in C- changing chars to ints


I am currently working on a project that requires a priority queue in C. I am using the code from Rosettacode.org.

I am attempting to modify the priority queue so that it takes an integer instead of a character. I tried changing all of the variable types but I am getting the following error.

test.c:62:16: warning: incompatible integer to pointer conversion passing 'int' to parameter of type 'int *' [-Wint-conversion]

This works perfectly when its a char, but suddenly stops when its an int. Why is this happening? Here is my code:

#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;
}

Solution

  • In your push() function signature, the third argument is of type int *, but you're sending an int while calling it. Pointer to integer conversion is an implementation specific behavior and is has high potential for causing undefined behavior.

    As I see it, you don't need data to be a pointer, a simple int everywhere should do the job.