data-structures · intermediate · ~15 min
Modular indexing for a ring buffer.
Build a fixed-capacity FIFO queue of ints on top of a circular (ring) buffer.
The grader supplies this struct:
typedef struct { int *data; size_t cap, len, head; } iqueue_t;
Implement these functions (no main — the grader calls them):
int queue_init(iqueue_t *q, size_t cap) — allocate data to hold cap ints; return 0, or -1 on allocation failure.void queue_free(iqueue_t *q) — free storage and reset fields.int queue_enqueue(iqueue_t *q, int v) — add v at the tail; return 0, or -1 if the queue is full.int queue_dequeue(iqueue_t *q, int *out) — remove the front into *out; return 0, or -1 if empty.A sequence of enqueue/dequeue operations after queue_init. The capacity is fixed at init time; the buffer wraps around using modular indexing.
Each function returns its status code (above). Elements come out in first-in-first-out order. dequeue writes the removed value through out on success.
init cap=3
enqueue 1,2,3 -> all 0
enqueue 4 -> -1 (full)
dequeue -> out=1, returns 0
enqueue 4 -> 0 (slot reused via wrap-around)
dequeue,dequeue,dequeue -> 2, 3, 4
-1; dequeue on an empty queue returns -1.cap.(head, len); the tail index is (head + len) % cap. Use malloc/free.An iqueue_t pointer plus per-call args (capacity at init, value to enqueue, or out pointer for dequeue).
Status codes: 0 on success, -1 if full (enqueue) / empty (dequeue) / alloc fails (init); dequeued value via out.
Fixed capacity, circular buffer indexed modulo cap; FIFO order.
#include <stdlib.h>
#include <stddef.h>
int queue_init(iqueue_t *q, size_t cap){ /* TODO */ return -1; }
void queue_free(iqueue_t *q){ /* TODO */ }
int queue_enqueue(iqueue_t *q, int v){ /* TODO */ return -1; }
int queue_dequeue(iqueue_t *q, int *out){ /* TODO */ return -1; }
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.