I recently started learning a bit more about Data Structures and then, when implementing the Queue concept in C, I faced the following:
typedef struct {
int max; /* Max. enqueed items. */
int total; /* Total enqueued. */
int pos_start; /* Pos. of first item. */
int pos_end; /* Pos. of last item. */
int item_size; /* Byte size of each item. */
void** items; /* Array of items. */
} queue_t;
/*
* Omitted code for brevity purposes.
*/
void
queue_add(queue_t* queue, void* item)
{
if (queue_full(queue))
{
fprintf(stderr, "Tried to add an item into a full queue");
exit(1);
}
queue->items[queue->pos_end] = item;
queue->total++;
queue->pos_end = find_next_end(queue);
}
Apparently it works. A couple of notes:
- The original tutorial taught how to create a queue of integers. I tried to challenge myself by creating a queue of "any" element - that's the reason I'm trying to use an array of
void*
elements. - Due the fact I'm using an array of
void*
elements, I know that, whenever I want to use any item from this queue (e.g. in the main fuction by usingqueue_pop
), I need to do a proper casting. By using casting, the compiler can know exactly how many bytes that variable should take in memory.
However, my big question is:
Based on my function, when I push a new item into the queue, I save it into queue->items[queue->pos_end]
. If the compiler doesn't know how many bytes item
has (as it's marked as a void*
), how does it calculate the memory address for queue->items[queue->pos_end]
?