0

So I have to implement a circular queue using array and I've used the following code to do so. However, for some reason when I try to add the 5th element to my queue, it does not seem to work. ALso, it doesnt work when I try to dequeue after adding 4 elements in my queue.

typedef struct {
    int array[5],front,rear;
} cqueue;

void init(cqueue *q)
{
    q->front=q->rear=-1;
}

int enqueue(cqueue *q,int val){
    if(q->front==(((q->rear)+1)%5)){
        printf("Overflow");
        return 1;
    }
    else{
        q->front = (q->front==-1) ? 0:q->front;
        q->rear=(q->rear+1)%5;
        q->array[q->rear]=5;
        return 0;
    }
}

int dequeue(cqueue *q,int *d){
    if(q->front==q->rear){
        if(q->front==-1){
            printf("Underflow");
            return 1;
        }
        else{
            *d=q->array[q->front];
            q->rear=q->front=-1;
            return *d;
        }
    }
    else{
        *d=q->array[q->front];
        q->front=((q->front)+1)%5;
        return *d;
    }
}     

void display(cqueue *q){
    int n=q->front;
    do{
        printf("%d\n",q->array[n]);
        n=(n+1)%5;
    } while(n!=(q->rear+1)%5);
}

int main() {
        
    int i;
    cqueue *q1;
    init(q1);
    enqueue(q1,10);
    enqueue(q1,10);
    enqueue(q1,10);
    enqueue(q1,10);
    enqueue(q1,10);



    // dequeue(q1,&i);
    // dequeue(q1,&i);
    // enqueue(q1,10);
    display(q1);


        
    return 0;
    }

I don't know what to try or where I went wrong. Can anyone help?

3
  • 1
    I find that another member count is needed. Otherwise you can't tell whether the circular queue is full or empty. Commented Oct 7, 2022 at 15:10
  • 1
    @thetacodude These lines cqueue *q1; init(q1); invoke undefined behavior because the pointer q was not initialized. Commented Oct 7, 2022 at 15:10
  • @VladfromMoscow I initialized cqueue using malloc and it works fine now!! Thanks! Commented Oct 7, 2022 at 15:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.