I\'m trying to implement a skew heap in C, but my code doesn\'t compile. I\'m not that experienced in C and never created any type of heap in C. That is why I don\'t know how to
Regarding the compiler errors,
program.c: In function ‘skewHeapAdd’:
program.c:185: warning: implicit declaration of function ‘skewHeapMerge’
program.c:185: warning: assignment makes pointer from integer without a cast
tells you that no prototype of skewHeapMerge
is in scope where skewHeapAdd
is defined, hence (the compiler apparently operates in C89 mode, but thankfully warns about it), the compiler supposes an implicit declaration with return type int
for skewHeapMerge
.
Add a header file with prototypes for all your functions, and #include
that in all *.c
files where these functions are used or defined, so that the compiler knows the types of the functions.
program.c: In function ‘skewHeapRemoveFirst’:
program.c:191: warning: assignment makes pointer from integer without a cast
that should be the line
sk->root = skewHeapMerge(n->leftchild, n->rightchild);
where sk->root
is a struct node*
, but due to the implicit declaration of skewHeapMerge
, that is assumed to return an int
.
program.c: At top level:
program.c:196: error: conflicting types for ‘skewHeapMerge’
program.c:185: note: previous implicit declaration of ‘skewHeapMerge’ was here
here the compiler finds that the definition of skewHeapMerge
gives a type conflicting with the one from the implicit declaration.
program.c: In function ‘skewHeapMerge’:
program.c:202: error: incompatible types when returning type ‘struct node’ but ‘struct node *’ was expected
program.c:205: error: incompatible types when returning type ‘struct node’ but ‘struct node *’ was expected
That is for the lines
if (left == NULL)
return *right;
if (right == NULL)
return *left;
where you ought to return right
resp. left
instead of *right
resp. *left
(I overlooked that at first).
You have a mistake in skewHeapRemoveFirst
void skewHeapRemoveFirst (struct skewHeap *sk)
{
struct node * n = sk->root;
free(n);
sk->root = skewHeapMerge(n->leftchild, n->rightchild);
}
where you use n
after you free
d it. You have to exchange the last two lines in that function.
And in skewHeapMerge
struct node * skewHeapMerge(struct node *left, struct node *right)
{
struct node *temp = (struct node *) malloc(sizeof(struct node));
if (left == NULL)
return *right;
if (right == NULL)
return *left;
you are leaking memory. Remove the allocation, since if temp
is used at all, you assign either left->leftchild
or right->rightchild
to it.