LearnFrenzy
Sign in Take a free test

Typedef · typedef Programs · Question 2

Circular queue (ring buffer) with typedef struct in C Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

Implement a fixed-capacity circular queue type with enqueue and dequeue that report "full" and "empty".

Solution
main.c
#include <stdbool.h>
#include <stdio.h>

#define CAP 3

typedef struct {
    int items[CAP];
    int head, count;              /* head = index of the oldest item */
} Queue;

bool enqueue(Queue *q, int v) {
    if (q->count == CAP)
        return false;
    q->items[(q->head + q->count) % CAP] = v;   /* wrap around the end */
    q->count++;
    return true;
}

bool dequeue(Queue *q, int *v) {
    if (q->count == 0)
        return false;
    *v = q->items[q->head];
    q->head = (q->head + 1) % CAP;
    q->count--;
    return true;
}

int main(void) {
    Queue q = {.head = 0, .count = 0};
    for (int v = 1; v <= 4; v++)
        if (!enqueue(&q, v))
            printf("enqueue %d: queue full\n", v);
    int v;
    dequeue(&q, &v);
    printf("dequeued %d\n", v);
    enqueue(&q, 4);
    printf("rest:");
    while (dequeue(&q, &v))
        printf(" %d", v);
    printf("\n");
    return 0;
}

Output Verified by compiling and running

enqueue 4: queue full
dequeued 1
rest: 2 3 4

The modulo makes indexes wrap around, so freed slots at the front are reused without moving any data. Keeping a count avoids the classic ambiguity of head == tail meaning both "full" and "empty".

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links