I have an array of structs (actually it\'s a heap array sorted by priority).
typedef struct {
char name[MAX_CHARACTERS+1];
int priority;
} person;
perso
An array is a continuous block of memory. So if you want to remove the first element, you have to move all the following elements towards the beginning by one element:
void remove(void)
{
memmove(&p[0], &p[1], (MAX_HEAPSIZE - 1) * sizeof(person));
}
This is pretty inefficient. Popping the first element is a common operation with a heap, so you'd usually do it the other way around - remove the last element of an array - which is very fast, because the other elements of the array aren't affected.
void remove(void)
{
heapsize--;
}
heapsize
can then be used as the index of the top element of the heap (assuming you preserve the heap property, of course).
If you want to overwrite the first element of the array with the last one and zero out the memory of the last element, which is not used anymore, you can use memcpy and memset:
void remove(void)
{
memcpy(&p[0], &p[heapsize - 1], sizeof(person));
memset(&p[heapsize - 1], 0x00, sizeof(person));
}
Zeroing out the memory of the last element is not strictly necessary, though, because you shouldn't be accessing it in the first place. Instead of overwriting the first element with the last using memcpy, it can also be done with strcpy
and assignment of the priority (like in your remove
); using memcpy is simply easier.