C Program: Dynamic Priority Queue & Extract Max
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Dynamically Allocate Memory for a Priority Queue and Insert/Extract Elements by Priority

📑 On this page:
  • Purpose & Objective
  • What is a Priority Queue?
  • Why a Binary Max-Heap?
  • 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 priority queue with a struct PQNode (data + priority)
  • How to allocate the queue and its internal array with malloc()
  • How to insert with sift-up to keep the max-heap property
  • How to extract the maximum with sift-down
  • Why a max-heap gives O(log n) insert and extract
  • How to free the queue in the correct order

Purpose & Objective

To develop a C program that dynamically allocates memory for a priority queue and implements functions to insert and extract priority-based elements, we will carefully present each step. This program demonstrates key priority-queue operations with dynamic memory allocation in C and explains practical, real-life applications.

Purpose:

  1. Priority Queues: Using dynamic memory allocation to build a priority-based data structure where elements are stored, created, and retrieved according to their priority value.
  2. Dynamic Memory Allocation: Learning how to distribute memory dynamically among the queue's main elements to handle different priorities and sizes at runtime.

💡 Quick Definition: A priority queue is an abstract data type where each element has a priority. The element with the highest priority is always extracted first, regardless of insertion order. The most efficient implementation is a binary heap.

C program to dynamically allocate memory for a priority queue and insert/extract elements based on priority

What is a Priority Queue?

A priority queue behaves like a regular queue — but each element also carries a priority value. Operations:

Operation Action Complexity (heap)
insert(data, priority)Add an elementO(log n)
extractMax()Remove and return the highest-priority elementO(log n)
peek()Look at the highest-priority elementO(1)

Why a Binary Max-Heap?

A naive priority queue stores elements in an array and scans linearly on extract — that's O(n). A binary max-heap stores them in an array, but keeps a shape where each parent has a priority at least as large as its children. That guarantees the maximum is always at index 0, and both insert and extract can restore the invariant in O(log n).

Relationship Formula
Left child of i2*i + 1
Right child of i2*i + 2
Parent of i(i - 1) / 2

Real-Life Applications

Priority queues appear in many real-world scenarios:

Task Scheduling

Scheduling tasks or processes solely by priority levels. In task scheduling, a priority queue guarantees that high-priority work completes first. This is especially useful in network programming, operating systems, and real-time applications.

Job Management

Managing jobs and tasks in an operating system according to their importance — so critical processes always run before background tasks.

Event-Driven Simulations

Simulating discrete events with unique preferences for event order. Every simulation step extracts the next event by its scheduled time or priority.

Complete C Program

Program: Dynamically allocate a priority queue (max-heap) and insert / extract by priority

#include <stdio.h>
#include <stdlib.h>

/* Structure for a priority queue node */
struct PQNode {
    int data;
    int priority;
};

/* Structure for a priority queue */
struct PriorityQueue {
    struct PQNode* array;
    int capacity;
    int size;
};

/* Create a priority queue of given capacity */
struct PriorityQueue* createPriorityQueue(int capacity) {
    struct PriorityQueue* pq = (struct PriorityQueue*) malloc(sizeof(struct PriorityQueue));
    if (!pq) {
        printf("Memory allocation failed.\n");
        exit(1);
    }
    pq->capacity = capacity;
    pq->size = 0;
    pq->array = (struct PQNode*) malloc(capacity * sizeof(struct PQNode));
    if (!pq->array) {
        printf("Memory allocation failed.\n");
        free(pq);
        exit(1);
    }
    return pq;
}

/* Swap two priority queue nodes */
void swap(struct PQNode* a, struct PQNode* b) {
    struct PQNode temp = *a;
    *a = *b;
    *b = temp;
}

/* Heapify a subtree rooted at index i */
void heapify(struct PriorityQueue* pq, int i) {
    int largest = i;
    int left = 2 * i + 1;
    int right = 2 * i + 2;

    if (left < pq->size && pq->array[left].priority > pq->array[largest].priority)
        largest = left;

    if (right < pq->size && pq->array[right].priority > pq->array[largest].priority)
        largest = right;

    if (largest != i) {
        swap(&pq->array[i], &pq->array[largest]);
        heapify(pq, largest);
    }
}

/* Insert an element into the priority queue */
void insert(struct PriorityQueue* pq, int data, int priority) {
    int i;
    struct PQNode newNode;

    if (pq->size == pq->capacity) {
        printf("Priority queue is full. Cannot insert.\n");
        return;
    }

    newNode.data = data;
    newNode.priority = priority;
    pq->array[pq->size] = newNode;
    pq->size++;

    /* Sift up to maintain heap property */
    i = pq->size - 1;
    while (i != 0 && pq->array[(i - 1) / 2].priority < pq->array[i].priority) {
        swap(&pq->array[i], &pq->array[(i - 1) / 2]);
        i = (i - 1) / 2;
    }
}

/* Extract the element with highest priority */
struct PQNode extractMax(struct PriorityQueue* pq) {
    struct PQNode root;
    struct PQNode emptyNode;

    if (pq->size <= 0) {
        printf("Priority queue is empty. Cannot extract.\n");
        emptyNode.data = 0;
        emptyNode.priority = 0;
        return emptyNode;
    }
    if (pq->size == 1) {
        pq->size--;
        return pq->array[0];
    }

    root = pq->array[0];
    pq->array[0] = pq->array[pq->size - 1];
    pq->size--;
    heapify(pq, 0);
    return root;
}

/* Display the priority queue */
void displayPriorityQueue(struct PriorityQueue* pq) {
    int i;
    printf("Priority Queue elements:\n");
    for (i = 0; i < pq->size; ++i)
        printf("(%d, %d) ", pq->array[i].data, pq->array[i].priority);
    printf("\n");
}

/* Free all memory */
void freePriorityQueue(struct PriorityQueue* pq) {
    if (pq) {
        if (pq->array)
            free(pq->array);
        free(pq);
    }
}

/* Main function to demonstrate priority queue operations */
int main() {
    int capacity, choice, data, priority;
    struct PriorityQueue* pq;
    struct PQNode node;

    printf("Enter the capacity of the priority queue: ");
    scanf("%d", &capacity);

    pq = createPriorityQueue(capacity);

    while (1) {
        printf("\nPriority Queue Operations:\n");
        printf("1. Insert Element\n");
        printf("2. Extract Maximum Element\n");
        printf("3. Display Priority Queue\n");
        printf("4. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                printf("Enter element and its priority to insert: ");
                scanf("%d %d", &data, &priority);
                insert(pq, data, priority);
                break;
            case 2:
                printf("Extracting maximum priority element...\n");
                node = extractMax(pq);
                if (node.priority != 0)
                    printf("Extracted element: (%d, %d)\n", node.data, node.priority);
                break;
            case 3:
                displayPriorityQueue(pq);
                break;
            case 4:
                printf("Exiting program.\n");
                freePriorityQueue(pq);
                exit(0);
            default:
                printf("Invalid choice. Please try again.\n");
        }
    }

    return 0;
}
                                    

Program Output

Enter the capacity of the priority queue: 5

Priority Queue Operations:
1. Insert Element
2. Extract Maximum Element
3. Display Priority Queue
4. Exit
Enter your choice: 1
Enter element and its priority to insert: 10 3

Priority Queue Operations:
1. Insert Element
2. Extract Maximum Element
3. Display Priority Queue
4. Exit
Enter your choice: 1
Enter element and its priority to insert: 20 1

Priority Queue Operations:
1. Insert Element
2. Extract Maximum Element
3. Display Priority Queue
4. Exit
Enter your choice: 1
Enter element and its priority to insert: 30 2

Priority Queue Operations:
1. Insert Element
2. Extract Maximum Element
3. Display Priority Queue
4. Exit
Enter your choice: 2
Extracting maximum priority element...
Extracted element: (10, 3)

Priority Queue Operations:
1. Insert Element
2. Extract Maximum Element
3. Display Priority Queue
4. Exit
Enter your choice: 3
Priority Queue elements:
(20, 1) (30, 2)

Priority Queue Operations:
1. Insert Element
2. Extract Maximum Element
3. Display Priority Queue
4. Exit
Enter your choice: 1
Enter element and its priority to insert: 40 5

Priority Queue Operations:
1. Insert Element
2. Extract Maximum Element
3. Display Priority Queue
4. Exit
Enter your choice: 1
Enter element and its priority to insert: 50 4

Priority Queue Operations:
1. Insert Element
2. Extract Maximum Element
3. Display Priority Queue
4. Exit
Enter your choice: 2
Extracting maximum priority element...
Extracted element: (40, 5)

Priority Queue Operations:
1. Insert Element
2. Extract Maximum Element
3. Display Priority Queue
4. Exit
Enter your choice: 4
Exiting program.
                                

Step-by-Step Explanation

Let's break down this program section by section:

1. Data structures:

struct PQNode { int data; int priority; };
struct PriorityQueue { struct PQNode* array; int capacity; int size; };
                                

Each element stores both a data value and a priority. The queue holds a dynamically allocated array of these nodes plus the current size and capacity.

2. Create the queue:

pq = (struct PriorityQueue*) malloc(sizeof(struct PriorityQueue));
pq->array = (struct PQNode*) malloc(capacity * sizeof(struct PQNode));
                                

Two allocations: the queue struct and the internal array. If the second fails, the first is freed before exiting — that's proper error handling.

3. Insert with sift-up:

pq->array[pq->size] = newNode;
pq->size++;
i = pq->size - 1;
while (i != 0 && pq->array[(i - 1) / 2].priority < pq->array[i].priority) {
    swap(&pq->array[i], &pq->array[(i - 1) / 2]);
    i = (i - 1) / 2;
}
                                

Append at the end, then bubble up: while the new node's priority is greater than its parent's, swap them and move up. At most log n swaps.

4. Extract max with sift-down:

root = pq->array[0];
pq->array[0] = pq->array[pq->size - 1];
pq->size--;
heapify(pq, 0);
                                

The max is always at index 0. Save it, replace with the last element, shrink the queue, then sift-down from index 0 — the standard heap-removal trick.

5. Heapify (sift-down):

if (left < pq->size && pq->array[left].priority > pq->array[largest].priority)
    largest = left;
if (right < pq->size && pq->array[right].priority > pq->array[largest].priority)
    largest = right;
if (largest != i) {
    swap(&pq->array[i], &pq->array[largest]);
    heapify(pq, largest);
}
                                

Find the largest of the current node and its two children, swap if needed, then recurse. This is the standard max-heap restore.

6. Free memory:

free(pq->array);
free(pq);
                                

Order matters: free the inner array first, then the struct. Reversing the order would leave a dangling pointer inside a freed struct.

🎯 Key Takeaway: A priority queue is just a heap in disguise. Once you master the two primitive operations — sift-up for insert, sift-down for extract — you own every other heap-based algorithm: heapsort, Dijkstra, A*, task schedulers, and top-K queries.

Frequently Asked Questions

1. Why use a max-heap and not a min-heap?

Either works — it's a choice. A max-heap extracts the highest priority first, a min-heap extracts the lowest. This program uses a max-heap because "highest priority wins" matches common intuition. For a min-priority queue (e.g., earliest deadline first), invert the comparison.

2. What does the "priority != 0" check do in main?

When extractMax is called on an empty queue, it returns a dummy node with priority 0. The caller checks if (node.priority != 0) before printing, so a dummy isn't displayed as a successful extraction.

3. Why is it a bad idea to use priority 0 as a real value?

Because 0 is the sentinel we use to signal "empty". If you actually want priorities at 0, replace the sentinel with a separate return value or a status flag. Better yet, restructure the API to return a status code and use an output parameter.

4. What's the total time to insert n elements and extract all of them?

Each insert is O(log n) and each extract is O(log n), so n inserts + n extracts = O(n log n) total. That's exactly heapsort. Building all elements up front with Floyd's trick would make the build O(n), but the full insert+extract cycle is still O(n log n).

💡 Tip: Compile with gcc -fsanitize=address -g to catch leaks and use-after-free instantly.

📖 Related Tutorials

  • malloc in C
  • free in C
  • 6. Dynamic Binary Search Tree
  • 7. Dynamic Queue — Enqueue and Dequeue
  • 8. Dynamic Graph — Add Vertices and Edges
  • All DMA Assignments

Previous :-->> 8. Write a C program that dynamically allocates memory for a graph data structure and implements functions to add vertices and edges.
 -->> NEXT: Real Life Case study in program Using C
-->>ALL Dynamic Memory Allocation assignments in c


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.