- 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:
- 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.
- 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.
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 element | O(log n) |
extractMax() | Remove and return the highest-priority element | O(log n) |
peek() | Look at the highest-priority element | O(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 i | 2*i + 1 |
Right child of i | 2*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.
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