Creating a Graph in C

Intermediate
6 min read
Updated: Nov 2026
1 example

A Reusable Graph Struct

A reusable graph type bundles the vertex count, the matrix, and an edge count. Allocate the matrix with calloc so every cell starts at 0, and expose small functions like graph_new, graph_add, degree, and graph_free. Ignoring duplicate edges keeps the edge count accurate.

Remember
struct Graph { int n; int *m; int edges; };
g->m = calloc((size_t)n * n, sizeof *g->m);
g->m[u * g->n + v] = 1;

Cheat Sheet

Keep these facts handy while you work with Creating a Graph in C in C.

TopicDetail
Allocatecalloc(n * n, ...)
Indexm[u * n + v]
Duplicate edgesCheck before counting
FreeMatrix, then struct

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Breadth-First Search (BFS) in C.

Example 1 — Build a five-vertex graph

A duplicate edge is ignored.

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

struct Graph { int n; int *m; int edges; };

static struct Graph *graph_new(int n) {
    struct Graph *g = malloc(sizeof *g);
    if (!g) exit(1);
    g->n = n;
    g->edges = 0;
    g->m = calloc((size_t)n * n, sizeof *g->m);
    if (!g->m) exit(1);
    return g;
}

static void graph_add(struct Graph *g, int u, int v) {
    if (!g->m[u * g->n + v]) {
        g->m[u * g->n + v] = 1;
        g->m[v * g->n + u] = 1;
        g->edges++;
    }
}

static int degree(const struct Graph *g, int v) {
    int d = 0;
    for (int i = 0; i < g->n; i++) d += g->m[v * g->n + i];
    return d;
}

int main(void) {
    struct Graph *g = graph_new(5);
    graph_add(g, 0, 1); graph_add(g, 0, 4);
    graph_add(g, 1, 2); graph_add(g, 1, 3); graph_add(g, 1, 4);
    graph_add(g, 1, 0);

    printf("vertices=%d edges=%d\n", g->n, g->edges);
    printf("degree(1)=%d degree(3)=%d\n", degree(g, 1), degree(g, 3));

    free(g->m);
    free(g);
    return 0;
}

How It Works

  1. calloc zeroes the matrix so no edges exist initially.
  2. The call graph_add(g, 1, 0) repeats edge 0-1 and is ignored.
  3. Vertex 1 connects to 0, 2, 3, and 4.

Edge Cases & Pitfalls

Check these before relying on Creating a Graph in C in real programs.

overflow

Index math

u * n + v must stay inside n * n; validate vertex numbers.

free

Freeing only the struct

Free the matrix before the struct that holds the pointer.

Key Takeaways

  • Struct holds n, matrix, edges.
  • calloc zero-initializes.
  • Free in the right order.

One line: A reusable graph type bundles the vertex count, the matrix, and an edge count.

Frequently Asked Questions

Define a struct holding the vertex count and an adjacency matrix or list, then write functions to add edges, query neighbors, and free memory.
It allocates and zeroes the memory, so all entries start as "no edge".
Continue with "Breadth-First Search (BFS) in C" next. Explore a graph with a queue and compute shortest hop distances. The C Graphs hub lists every topic in order.

Next: Breadth-First Search (BFS) in C

Explore a graph with a queue and compute shortest hop distances.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful