- How to model a queue with
struct Queue(front,rear,size,capacity,int *array) - How to allocate both the queue struct and the internal array with
malloc() - How to implement enqueue (add to rear) and dequeue (remove from front) in O(1)
- How the modulo operator
%makes the queue circular - How to free the queue in the correct order β inner array first, struct second
Purpose & Objective
To extend a program in C that allocates memory dynamically for a queue data structure and implements enqueue and dequeue operations, we will cover each aspect step by step. This program demonstrates the main actions of a queue using dynamic memory allocation, explains the purpose and real-life applications, and provides a detailed code explanation.
Purpose:
- Understanding Queues: Implementing a queue data structure using dynamic memory allocation helps grasp the fundamentals of FIFO (First In First Out) systems in computer science.
- Dynamic Memory Allocation: Learning how to dynamically allocate memory for data structures to handle variable storage requirements at runtime.
π‘ Quick Definition: A queue is a FIFO data structure β the first element enqueued is the first one dequeued. A circular queue reuses freed slots by wrapping front and rear back to index 0 using the modulo operator.
What is a Queue (FIFO)?
A queue is a linear data structure with two operations at opposite ends:
| Operation | Action | Error Condition |
|---|---|---|
enqueue(x) | Add x to the rear | Queue is full |
dequeue() | Remove and return the front element | Queue is empty |
Why a Circular Queue?
In a naΓ―ve array-based queue, front and rear only move forward. After a few dequeues, the front of the array becomes wasted space β even though the queue isn't full, you can't enqueue anymore. A circular queue fixes this by wrapping around with modulo arithmetic.
| Action | Pointer Update |
|---|---|
| enqueue | rear = (rear + 1) % capacity |
| dequeue | front = (front + 1) % capacity |
Real-Life Applications
Following are some of the real-life applications of queues:
Task Scheduling
Operating systems use queues to decide which processes are waiting to run. Queue scheduling is one of the principal tools that determine the execution order of threads or processes. Multiple operations are enqueued, and the scheduler picks them in order.
Resource Management
Print queue control systems hold jobs waiting to print. Automatically managing print jobs and print queues from a central management client lets you set rules for disaster recovery, print broadcasting, and load balancing β and remote-control all direct print traffic across the company.
Data Buffering
Network applications use queues to buffer data packets while waiting for transmission. The first packet arrives first and is transmitted first when the next slot opens up. Queues hold incoming data before processing β for example, holding incoming packets in a network before sending them to a lower destination.
Complete C Program
Program: Dynamically allocate a circular queue and implement enqueue and dequeue
#include <stdio.h>
#include <stdlib.h>
/* Structure for a circular queue */
struct Queue {
int front, rear, size;
unsigned capacity;
int *array;
};
/* Function to create a queue of given capacity */
struct Queue *createQueue(unsigned capacity) {
struct Queue *queue = (struct Queue *)malloc(sizeof(struct Queue));
if (queue == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
queue->capacity = capacity;
queue->front = queue->size = 0;
queue->rear = capacity - 1; /* Important for circular implementation */
queue->array = (int *)malloc(queue->capacity * sizeof(int));
if (queue->array == NULL) {
printf("Memory allocation failed.\n");
free(queue);
exit(1);
}
return queue;
}
/* Function to check if the queue is full */
int isFull(struct Queue *queue) {
return (queue->size == queue->capacity);
}
/* Function to check if the queue is empty */
int isEmpty(struct Queue *queue) {
return (queue->size == 0);
}
/* Function to add an element to the queue (enqueue) */
void enqueue(struct Queue *queue, int item) {
if (isFull(queue)) {
printf("Queue is full. Cannot enqueue.\n");
return;
}
queue->rear = (queue->rear + 1) % queue->capacity;
queue->array[queue->rear] = item;
queue->size++;
printf("%d enqueued to the queue.\n", item);
}
/* Function to remove an element from the queue (dequeue) */
int dequeue(struct Queue *queue) {
int item;
if (isEmpty(queue)) {
printf("Queue is empty. Cannot dequeue.\n");
return -1;
}
item = queue->array[queue->front];
queue->front = (queue->front + 1) % queue->capacity;
queue->size--;
return item;
}
/* Function to display the queue contents */
void displayQueue(struct Queue *queue) {
int i;
if (isEmpty(queue)) {
printf("Queue is empty.\n");
return;
}
printf("Queue elements: ");
for (i = queue->front; i != queue->rear; i = (i + 1) % queue->capacity) {
printf("%d ", queue->array[i]);
}
printf("%d\n", queue->array[queue->rear]);
}
/* Main function to demonstrate queue operations */
int main() {
struct Queue *queue = NULL;
int choice, item, capacity;
printf("Enter the capacity of the queue: ");
scanf("%d", &capacity);
queue = createQueue(capacity);
while (1) {
printf("\nQueue Operations:\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter element to enqueue: ");
scanf("%d", &item);
enqueue(queue, item);
break;
case 2:
item = dequeue(queue);
if (item != -1) {
printf("Dequeued element: %d\n", item);
}
break;
case 3:
displayQueue(queue);
break;
case 4:
printf("Exiting program.\n");
free(queue->array);
free(queue);
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}
Program Output
Enter the capacity of the queue: 5
Queue Operations:
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 1
Enter element to enqueue: 10
10 enqueued to the queue.
Queue Operations:
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 1
Enter element to enqueue: 20
20 enqueued to the queue.
Queue Operations:
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 1
Enter element to enqueue: 30
30 enqueued to the queue.
Queue Operations:
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 3
Queue elements: 10 20 30
Queue Operations:
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 2
Dequeued element: 10
Queue Operations:
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 3
Queue elements: 20 30
Queue Operations:
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 4
Exiting program.
Step-by-Step Explanation
Let's break down this program section by section:
1. Include header files and define the structure:
struct Queue {
int front, rear, size;
unsigned capacity;
int *array;
};
front is the index of the oldest element. rear is the index of the newest. size is how many elements are currently in the queue. capacity is the maximum. array is the dynamically allocated block holding the elements.
2. Create the queue with malloc:
queue = (struct Queue *)malloc(sizeof(struct Queue));
queue->front = queue->size = 0;
queue->rear = capacity - 1;
queue->array = (int *)malloc(queue->capacity * sizeof(int));
Two allocations: one for the struct itself, one for the internal array. Initializing rear = capacity - 1 matters β the first enqueue computes rear = (capacity - 1 + 1) % capacity = 0, so the first item lands at index 0.
3. Enqueue:
queue->rear = (queue->rear + 1) % queue->capacity;
queue->array[queue->rear] = item;
queue->size++;
The modulo operator wraps rear back to 0 when it passes the last index. That's the core of the circular behavior β slots freed by dequeues can be reused.
4. Dequeue:
item = queue->array[queue->front];
queue->front = (queue->front + 1) % queue->capacity;
queue->size--;
return item;
Symmetric to enqueue. Read the front value, advance front with the same modulo, decrement size. Both enqueue and dequeue are O(1).
5. Display:
for (i = queue->front; i != queue->rear; i = (i + 1) % queue->capacity) {
printf("%d ", queue->array[i]);
}
printf("%d\n", queue->array[queue->rear]);
The i != rear condition stops one element early so the last element can be printed without a trailing space. This is the cleanest way to iterate a circular queue.
6. Freeing memory before exit:
free(queue->array);
free(queue);
exit(0);
Order matters: free the inner array first, then the struct. Reverse order would leave a dangling array pointer inside the freed struct β technically not a bug here (you're exiting anyway), but bad practice.
π― Key Takeaway: A dynamic circular queue is an array plus two modulo-arithmetic indices. That's the entire data structure. Once you understand (rear + 1) % capacity, you understand circular buffers β the same pattern used in audio playback, network ring buffers, and keyboard input.
Frequently Asked Questions
1. Why does rear start at capacity - 1 instead of -1?
If rear started at -1, the first enqueue would compute (-1 + 1) % capacity = 0 β also correct. Starting at capacity - 1 means the first enqueue computes (capacity - 1 + 1) % capacity = 0 β same result. Either works, but the capacity - 1 form matches the classic circular-queue idiom.
2. What is the difference between a linear and a circular queue?
A linear queue wastes space after a few dequeues because front and rear only move forward. A circular queue wraps them around, reusing freed slots β so the queue can stay full as long as elements keep cycling through.
3. Why does dequeue return -1 on empty?
Because -1 is outside the range of values we expect (all our test data is positive). It's a sentinel value β the caller checks if (item != -1) to know the operation succeeded. In production, you might return a status code instead.
4. Can the queue grow after creation?
Not in this version. If you need growth, use realloc() on queue->array when full. That requires care β the modulo arithmetic must then use the new capacity, and you'd need to copy wrapped elements if front > rear.
π‘ Tip: Compile with gcc -fsanitize=address -g to catch leaks and use-after-free instantly.