I have in my C code an array of elements inside an heap structure defined as
typedef struct Elem {
void *key;
void *value;
} Elem;
typedef struct Heap {
unsigned int size;
unsigned int capacity;
Elem **array;
compareFunction compare;
} Heap;
For the element insertion function, I use this pseudo-code for add a custom element inside the heap array
Insert (H, x)
HeapSize(H) := HeapSize(H)+ 1
i := HeapSize(H)
H[i] = x
while i > 1 and H[Parent(i)] < H[i] do
exchange(H[i], H[Parent(i)])
i := Parent(i)
But during the assignment, especially after adding 4 elements, on the 5th call of this function a strange behavior happens in this line H[i] = x
for (k = 0; k < hpSize(hp) - 1; k++)
printf("%dn", *((int *)hpGetEl(hp, k)->key));
if (hpSize(hp) > 1)
printf("%dn", *((int *)(hp->array[0])->key));
printf("i: %dn", i);
hp->array[i] = hpCreateElem(key, value);
printf("%dn", *((int *)(hp->array[0])->key));
for (k = 0; k < hpSize(hp); k++)
printf("%dn", *((int *)hpGetEl(hp, k)->key));
The output of the debugging printf
is
1
4
2
3
---
1
i: 4
4198800
---
4198800
4
2
3
7
The assignment change the value of the key
inside the first element of the array and insert the new element on the 5th position. How is this possibile?
The hpCreateElem
function is defined as
Elem *hpCreateElem(void *key, void *value)
{
Elem *el;
el = (struct Elem *) malloc(sizeof(struct Elem));
if (el == NULL) return NULL;
el->key = key;
el->value = value;
return el;
}
Aucun commentaire:
Enregistrer un commentaire