C Program: Dynamic Queue & Enqueue/Dequeue
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Dynamically Allocate Memory for a Queue and Implement Enqueue and Dequeue Operations

πŸ“‘ On this page:
  • Purpose & Objective
  • What is a Queue (FIFO)?
  • Why a Circular Queue?
  • Real-Life Applications
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
πŸ“š In this program, you will learn:
  • 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:

  1. 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.
  2. 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.

C program to dynamically allocate memory for a queue data structure and implement enqueue and dequeue operations

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 rearQueue is full
dequeue()Remove and return the front elementQueue 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
enqueuerear = (rear + 1) % capacity
dequeuefront = (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.

πŸ“– Related Tutorials

  • malloc in C
  • free in C
  • 5. Dynamic Stack β€” Push and Pop
  • 6. Dynamic Binary Search Tree
  • 8. Dynamic Graph β€” Add Vertices and Edges
  • All DMA Assignments

Previous Topic: -->> 6. Dynamic Binary Search Tree   ||   Next topic: -->> 8. Dynamic Graph & Add Vertices/Edges


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.