C Program: Dynamic Graph & Add Vertices/Edges
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Dynamically Allocate Memory for a Graph and Implement Add Vertices and Edges

📑 On this page:
  • Purpose & Objective
  • What is a Graph?
  • Adjacency List vs Adjacency Matrix
  • 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 graph with an adjacency list using dynamic memory
  • How to allocate nodes with malloc() and check for NULL
  • How to add edges to an undirected graph (both directions)
  • How to traverse and print the graph
  • How to free the graph in the correct order — nodes → array → struct

Purpose & Objective

To expand a C program that dynamically allocates memory for a graph structure and implements functions to add vertices and edges, we will cover every step systematically. This program illustrates the essential operations of graph manipulation using dynamic memory allocation in C, explains real-life applications, and presents a detailed code explanation with output.

Purpose:

  1. Understanding Graph Data Structures: Implementing a graph using dynamic memory allocation builds an understanding of vertices and edges — fundamental to representing relationships between entities.
  2. Dynamic Memory Allocation: Learn how to allocate memory dynamically for graph nodes and edges to accommodate varying graph sizes and structures at runtime.

💡 Quick Definition: A graph is a set of vertices (nodes) connected by edges. In an undirected graph, an edge from A to B is the same as one from B to A — that's why we add two entries per edge in an adjacency list.

C program to dynamically allocate memory for a graph data structure and implement functions to add vertices and edges

What is a Graph?

A graph is a data structure consisting of:

  • Vertices (V): The individual entities — cities, users, network devices, or any object.
  • Edges (E): The connections between vertices — roads, friendships, links.

Graphs can be directed (edge has a direction) or undirected (edge is bidirectional). They can be weighted (each edge has a cost) or unweighted. This program builds an unweighted, undirected graph.

Adjacency List vs Adjacency Matrix

There are two common ways to store a graph. This program uses the adjacency list because it's memory-efficient for sparse graphs.

Approach Memory Best for
Adjacency MatrixO(V²)Dense graphs where V is small
Adjacency ListO(V + E)Sparse graphs, dynamic graphs

Real-Life Applications

Graphs are used to model relationships in real-world systems. Here are common examples:

Social Networks

Users are vertices, and friendships are edges. Friend-of-a-friend suggestions are computed by graph traversal.

Transportation Networks

Cities are vertices, and roads are edges. Route planning, shortest paths, and traffic optimization are graph algorithms.

Computer Networks

Devices (routers, switches, hosts) are vertices, and physical or logical connections are edges. Routing tables are essentially graph lookups.

Complete C Program

Program: Dynamically allocate a graph and add vertices and edges

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

/* Structure for an adjacency list node */
struct AdjListNode {
    int dest;
    struct AdjListNode* next;
};

/* Structure for adjacency list of each vertex */
struct AdjList {
    struct AdjListNode *head;
};

/* Structure for a graph */
struct Graph {
    int V;                     /* Number of vertices */
    struct AdjList* array;     /* Array of adjacency lists */
};

/* Function to create a new adjacency list node */
struct AdjListNode* newAdjListNode(int dest) {
    struct AdjListNode* newNode = (struct AdjListNode*) malloc(sizeof(struct AdjListNode));
    if (!newNode) {
        printf("Memory allocation failed.\n");
        exit(1);
    }
    newNode->dest = dest;
    newNode->next = NULL;
    return newNode;
}

/* Function to create a graph of V vertices */
struct Graph* createGraph(int V) {
    int i;
    struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph));
    if (!graph) {
        printf("Memory allocation failed.\n");
        exit(1);
    }
    graph->V = V;

    graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList));
    if (!graph->array) {
        printf("Memory allocation failed.\n");
        exit(1);
    }

    /* Initialize each adjacency list as empty */
    for (i = 0; i < V; ++i)
        graph->array[i].head = NULL;

    return graph;
}

/* Function to add an edge to an undirected graph */
void addEdge(struct Graph* graph, int src, int dest) {
    struct AdjListNode* newNode;

    /* Add an edge from src to dest */
    newNode = newAdjListNode(dest);
    newNode->next = graph->array[src].head;
    graph->array[src].head = newNode;

    /* Since the graph is undirected, add an edge from dest to src too */
    newNode = newAdjListNode(src);
    newNode->next = graph->array[dest].head;
    graph->array[dest].head = newNode;
}

/* Function to print the graph */
void printGraph(struct Graph* graph) {
    int v;
    for (v = 0; v < graph->V; ++v) {
        struct AdjListNode* temp = graph->array[v].head;
        printf("Adjacency list of vertex %d\n", v);
        while (temp) {
            printf(" -> %d", temp->dest);
            temp = temp->next;
        }
        printf("\n");
    }
}

/* Function to free graph memory */
void freeGraph(struct Graph* graph) {
    int v;
    if (graph) {
        if (graph->array) {
            for (v = 0; v < graph->V; ++v) {
                struct AdjListNode* temp = graph->array[v].head;
                while (temp) {
                    struct AdjListNode* prev = temp;
                    temp = temp->next;
                    free(prev);
                }
            }
            free(graph->array);
        }
        free(graph);
    }
}

/* Main function to demonstrate graph operations */
int main() {
    int V, E, i;
    int src, dest;
    struct Graph* graph;

    printf("Enter the number of vertices in the graph: ");
    scanf("%d", &V);

    graph = createGraph(V);

    printf("Enter the number of edges in the graph: ");
    scanf("%d", &E);

    printf("Enter the edges (src dest):\n");
    for (i = 0; i < E; ++i) {
        scanf("%d %d", &src, &dest);
        addEdge(graph, src, dest);
    }

    printf("Graph created successfully!\n");
    printf("Here is the adjacency list representation of the graph:\n");
    printGraph(graph);

    /* Free dynamically allocated memory */
    freeGraph(graph);

    return 0;
}
                                    

Program Output

Enter the number of vertices in the graph: 5
Enter the number of edges in the graph: 4
Enter the edges (src dest):
0 1
0 4
1 4
2 3
Graph created successfully!
Here is the adjacency list representation of the graph:
Adjacency list of vertex 0
 -> 4 -> 1

Adjacency list of vertex 1
 -> 4 -> 0

Adjacency list of vertex 2
 -> 3

Adjacency list of vertex 3
 -> 2

Adjacency list of vertex 4
 -> 1 -> 0
                                

Step-by-Step Explanation

Let's break down this program section by section:

1. Data structures:

struct AdjListNode { int dest; struct AdjListNode* next; };
struct AdjList     { struct AdjListNode *head; };
struct Graph       { int V; struct AdjList* array; };
                                

AdjListNode is one entry in an adjacency list — a destination vertex plus a pointer to the next entry. AdjList wraps the head pointer for a single vertex. Graph holds the vertex count and an array of AdjList.

2. Create the graph:

graph = (struct Graph*) malloc(sizeof(struct Graph));
graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList));
for (i = 0; i < V; ++i)
    graph->array[i].head = NULL;
                                

Two allocations: the graph struct, then the array of adjacency lists. Every list starts empty (head = NULL).

3. Add an edge:

newNode = newAdjListNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
/* repeat with src and dest swapped */
                                

Because the graph is undirected, every edge is stored twice: once under src pointing to dest, and once under dest pointing to src. This makes lookups fast in both directions. Prepending at the head is O(1).

4. Print the graph:

for (v = 0; v < graph->V; ++v) {
    printf("Adjacency list of vertex %d\n", v);
    temp = graph->array[v].head;
    while (temp) {
        printf(" -> %d", temp->dest);
        temp = temp->next;
    }
}
                                

For each vertex, walk its linked list and print every destination. Because we prepend, the order is reversed from insertion order — that's why vertex 0's list shows 4 -> 1 (4 was inserted last, so it's first in the list).

5. Free the graph:

for (v = 0; v < graph->V; ++v) {
    while (temp) { prev = temp; temp = temp->next; free(prev); }
}
free(graph->array);
free(graph);
                                

Order matters: first free every node in every adjacency list, then the array of lists, then the graph struct itself. Reversing the order would leave dangling pointers.

🎯 Key Takeaway: A graph as an adjacency list is really an array of linked lists. Once you see it that way — one linked list per vertex — every graph operation becomes a list traversal. That's why graphs feel less intimidating once you already know linked lists.

Frequently Asked Questions

1. Why does each edge get inserted twice?

Because this is an undirected graph — if A connects to B, then B connects to A. Storing both directions makes traversal from either side possible without special handling. For a directed graph, you'd add only one entry.

2. Why is the order reversed in the output?

Because addEdge prepends new nodes at the head of the list. If you insert edges in order 0-1, then 0-4, vertex 0's list ends up as 4 -> 1. If you want insertion order preserved, walk to the tail and append — but that costs O(degree) per edge instead of O(1).

3. Can I add vertices after creating the graph?

Not with this implementation — the array of adjacency lists is fixed-size. To add vertices, you'd need to realloc the array and initialize the new slot's head to NULL. That's a good follow-up exercise.

4. What's the memory footprint of this adjacency list?

O(V + E). The array holds V pointers, and each of the 2E edge nodes holds an int + a pointer. Compare to an adjacency matrix, which is O(V²) regardless of edge count — much heavier for sparse graphs.

💡 Tip: Compile with gcc -fsanitize=address -g to catch leaks and use-after-free bugs instantly — especially important with nested frees.

📖 Related Tutorials

  • malloc in C
  • free in C
  • 4. Dynamic Linked List and Reverse
  • 7. Dynamic Queue — Enqueue and Dequeue
  • 9. Dynamic Priority Queue
  • All DMA Assignments

Previous Topic: -->> 7. Dynamic Queue & Enqueue/Dequeue   ||   Next topic: -->> 9. Dynamic Priority Queue


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.