I am trying to implement a circular queue that takes a struct
- ⟶ checks if the queue is full if not enqueues ⟶ else return 0
- ⟶ checks if the queue is empty if not dequeues ⟶ else return 0
The following is my code :
#ifndef_QUEUE_H_
#define QUEUE_H_
#define QUEUE_SIZE 32
typedef struct queue
{
int head;
int tail;
int buffer[QUEUE_SIZE];
} queue_t;
void init_queue(queue_t *);
int enqueue(queue_t *, int);
int isfull(queue_t *);
int dequeue(queue_t *);
int queue_empty(queue_t *);
#endif
/* queue.h ends here */
/* *************************queue.c starts here************************ */
#include<queue.h>
#include<stm32f30x.h>
#define QUEUE_SIZE 32
int head;
int tail;
void init_queue(queue_t *q)
{
q->head = 0;
q->tail = 0;
}
int enqueue(queue_t *q, int a )
{
if ((((q->head)+1)%QUEUE_SIZE)!=q->tail)
{
q->buffer[q->head]=a;
q->head=(((q->head)+1)%QUEUE_SIZE);
return 1 ;
}
else
{
return 0 ;
}
}
int dequeue(queue_t *q)
{
int temp ;
if (queue_empty(q))
{
return 0;
}
else
{
temp = q->buffer[q->tail];
q->tail=((q->tail)+1)%QUEUE_SIZE;
return temp;
}
}
int queue_empty(queue_t *q)
{
if (q->head == q->tail)
{
return 1;
}
return 0;
}
/* **************queue.c ends here********************** */
When I try to test the queue: example enter "hello" and try to print the content inside it it prints "ello hlo elo.." and such incorrect replies.
I am using the enqueue and dequeue function in my getchar and putchar functions. Below are my getchar and putchar functions:
queue_t rxbuf;
queue_t txbuf;
int putchar(int c)
{
while(!(enqueue(&txbuf, c)));
}
int nonblockgetchar(void)
{
dequeue(&rxbuf);
}
int getchar(void)
{
int ch;
while (!(ch=dequeue(&rxbuf)));
return (ch);
}
Appreciate your time and help.