alexfort93
[H]ard|Gawd
- Joined
- Feb 21, 2008
- Messages
- 1,856
Hey all, need some help for my Systems Programming course. Trying to implement a queue...
So, I need to account for wrap-around. My idea was to store the address of the top and bottom blocks of memory, to use and compare. i.e. if the tail pointer was pointing to the same place as the bottom pointer, set it equal to the top pointer.
Just having trouble how to initally set the bottom pointer when I create_queue:
This is what I came up with, but not sure if it will work the way I want it to... Anyone have any input? Thanks.
Code:
struct queue {
void** head; // Pointer to top element in queue
void** tail; // Pointer to next open spot in queue
int max_cells; // Number of space in queue
int cells_used; // Number of cells used in queue
void* top; // Pointer to top of the queue
void* bottom; // Pointer to bottom of the queue
};
So, I need to account for wrap-around. My idea was to store the address of the top and bottom blocks of memory, to use and compare. i.e. if the tail pointer was pointing to the same place as the bottom pointer, set it equal to the top pointer.
Just having trouble how to initally set the bottom pointer when I create_queue:
Code:
Queue* create_queue(int max_cells) {
Queue* new_queue; // Holds pointer to the newly-allocated Queue structure.
new_queue = (Queue*) malloc(sizeof(Queue));
if (new_queue == NULL) return NULL; // Error--unable to allocate.
// Fill in the struct
new_queue->max_cells = max_cells;
new_queue->cells_used = 0; // Empty to start
// Now allocate space for the queue entries.
new_queue->head = (void**) calloc(sizeof(void*), max_cells);
if (new_queue->head == NULL) {
free(new_queue); // Unable to allocate queue entries, so free struct.
return NULL;
}
new_queue->tail = new_queue->head; // Start at the head
new_queue->top = new_queue->head; // Set top equal to the head
new_queue->bottom = new_queue->head + max_cells; // Set to bottom of the allocated space
return new_queue;
}
This is what I came up with, but not sure if it will work the way I want it to... Anyone have any input? Thanks.