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;
Reference
Cheat Sheet
Keep these facts handy while you work with Creating a Graph in C in 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;
}
Output
vertices=5 edges=5
degree(1)=4 degree(3)=1
How It Works
calloc zeroes the matrix so no edges exist initially.
The call graph_add(g, 1, 0) repeats edge 0-1 and is ignored.
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.
Remember
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.