I have a struct that contains pointer next
. I am trying to make a queue of the structs, but when I call enqueue/dequeue
I eventually get errors trying to write information; and don't know if it's due to enque/dequeue/insert
. Just learning C and not really sure of free/malloc
or if they're necessary. Insert is based on int value (smallest value first).
struct queue {
struct RCB* front;
struct RCB* back;
};
/*Initialize queue */
struct queue* new_queue(void){
struct queue* tmp = malloc( 1 * sizeof(tmp));
tmp->front = NULL;
tmp->back = NULL;
return tmp;
}
/*Add RCB to Queue FIFO */
struct queue* enqueue(struct queue* queue, struct RCB* rcb){
if(queue->front == NULL && queue->back == NULL){
queue->front = rcb;
queue->back = rcb;
printf("added front to queue\n");
return queue;
}
else {
queue->back->next = rcb;
queue->back = rcb;
printf("added to queue\n");
}
return queue;
}
/*Remove RCB from Queue FIFO */
struct RCB* dequeue(struct queue* queue){
struct RCB *tmp1 = (struct RCB *)malloc(sizeof(struct RCB));
struct RCB *tmp2 = (struct RCB *)malloc(sizeof(struct RCB));
if(queue->front == NULL && queue->back == NULL){
printf("queue is empty\n");
}
tmp1 = queue->front;
tmp2 = tmp1->next;
queue->front = tmp2;
if(queue->front == NULL){
queue->back = queue->front;
printf("removed rcb from queue\n");
}
return tmp1;
}
/*Insert RCB into Queue */
struct queue* insert(struct queue* queue, struct RCB* rcb){
if(queue->front == NULL && queue->back == NULL){
queue->front = rcb;
queue->back = rcb;
return queue;
}
if(queue->front->next == NULL){
queue->front->next = rcb;
return queue;
}
struct RCB *tmp = (struct RCB *)malloc(sizeof(struct RCB));
tmp = queue->front;
while(tmp->next->b2r < rcb->b2r || tmp->next == NULL){
tmp = tmp->next;
}
rcb->next = tmp->next;
tmp->next = rcb;
return queue;
}
Any help is greatly appreciated.