Most matrices in real programs are mostly zeros, and a sparse matrix format stores only the values that are not zero. The work is in recording where those values sit. This article builds the three standard formats in C and measures them against a plain dense array. On a 1024 by 1024 matrix with 1 percent of its cells filled, the compressed sparse row format (CSR) used 129,932 bytes where the dense array used 8,388,608, and it multiplied the matrix by a vector 105.79 times faster than the dense loop. At 50 percent filled, CSR still used three quarters of the dense memory and was only twice as fast.
The article covers the coordinate format (COO), CSR and the compressed sparse column format (CSC). For each one it shows how the format is built from a list of entries, how it multiplies a vector, and how much memory it needs. It then measures memory and multiply time at 1, 10 and 50 percent density, and ends with five bugs that compile cleanly and give wrong answers. The Arrays article covers the dense array used as the baseline. The code was built and tested with GCC 13.3, Clang 18.1.3 and MSVC 19.44.
What Is a Sparse Matrix?
A sparse matrix is a matrix with so few nonzero values that it is cheaper to store each value with its position than to store every cell. The three standard formats are COO, which keeps a row, a column and a value for each nonzero, CSR, which groups the values by row and replaces the row numbers with one pointer per row, and CSC, which does the same by column.
Whether a matrix is sparse enough is a matter of arithmetic. A dense n by n matrix of double values takes 8n² bytes. COO takes 16 bytes per nonzero: two 4-byte indexes and an 8-byte value. CSR and CSC take 12 bytes per nonzero, one index and one value, plus 4 bytes for each of the n + 1 pointers. For n = 1024, CSR is smaller than the dense array until about two thirds of the cells, 66.6 percent, are nonzero. Real sparse matrices are usually far below that line.
The three formats hold the same data and differ in what they make fast. CSR keeps each row’s values together, so a matrix-vector product y = A x reads them in order and writes each y[row] once. CSC keeps each column’s values together, which suits algorithms that work column by column. COO is the easiest to build, because new entries are simply appended, but its product has to read a row index for every value.
Sparse matrices are everywhere in practice. The adjacency matrix of a large graph is almost all zeros, and CSR is the same idea as an adjacency list packed into two arrays. Finite element models, recommendation data and word counts per document are sparse in the same way. The Wikipedia article covers the wider family of formats.
How This Was Measured
| Setting | Value |
|---|---|
| Date tested | December 5, 2026 |
| Hardware | Intel Core i7-8700K, 6 cores and 12 threads at 3.70 GHz, 32 GB RAM, Windows 11 Education build 26300 |
| Operating system | Ubuntu 24.04.5 under WSL2, kernel 5.15.146.1-microsoft-standard-WSL2, glibc 2.39, and Windows 11 for the MSVC build |
| Compilers | GCC 13.3 and Clang 18.1.3 at -O2 through CMake Release, MSVC 19.44 at /W4 /WX |
| Matrix | 1024 by 1024, so 1,048,576 cells, one fixed matrix per density |
| Densities | 1, 10 and 50 percent of the cells filled, at distinct positions |
| Generator | xorshift64 with seed 88172645463325252, values from -10.00 to 10.00 in steps of 0.01 |
| Products | y = A x with x[i] = (i % 7 – 3) × 0.5, timed over 100 products per format and density |
| Results | Allocated bytes per format, total milliseconds for 100 products, and CSR’s speedup over dense |
| Check | Every sparse product is compared with the dense product before timing, and the largest difference is printed |
The matrices are generated from a fixed seed, so the nonzero counts and the byte counts are the same on every run. The times are not. They depend on the machine and vary from run to run, so the tests check the table’s layout and its fixed columns but never a time. The times below come from one run.
COO: Coordinate Triplets
COO stores three arrays of equal length: the row of each nonzero, its column and its value. Building one means appending entries, much like a dynamic array. Matrix files usually arrive in this form, and two COO matrices can be added by joining their arrays.
Before COO is used for anything else, the builder sorts the entries by row and then by column and merges repeated positions by adding their values. Input often contains the same cell twice, for example when a finite element program adds the contributions of neighboring elements to one cell. The convention is that repeated entries are summed.
A COO product that simply adds every entry follows that convention and gets the right answer even with duplicates left in. The trouble starts in code that assumes each cell appears once. A conversion to a dense array that assigns values instead of adding them keeps only one of the duplicates, and the nonzero count is too high. The third pitfall shows that failure.
CSR: Compressed Sparse Row
CSR keeps the values sorted by row and stores no row numbers at all. Instead, an array of n + 1 row pointers marks where each row starts: row r occupies positions row_ptr[r] up to, but not including, row_ptr[r + 1]. The extra final pointer equals the number of nonzeros, so the last row has an end. Each nonzero costs one column index and one value.
The product follows the layout. For each row, the loop walks that row’s values and column indexes in memory order, multiplies each value by x[col], adds it to a running sum, and stores the sum in y[row]. The reads of the values and indexes are sequential, and y is written once per row. Only the reads of x jump around, following the column indexes.
CSR is the most widely used general-purpose sparse format, although some libraries, such as SuiteSparse and Eigen, default to CSC. CSR’s weakness is change: inserting one nonzero means shifting every later value and adding 1 to every later row pointer. CSR suits a matrix that is built once and then multiplied many times.
CSC: Compressed Sparse Column
CSC is CSR applied to columns. The values are sorted by column, an array of n + 1 column pointers marks where each column starts, and each nonzero stores its row index. The memory is identical to CSR. In fact, the CSC arrays of a matrix A are exactly the CSR arrays of its transpose.
For y = A x, the CSC loop walks one column at a time. Each value in column c is multiplied by x[c], which stays fixed for the whole column, and added into y at the value’s row. The reads are sequential, but the writes to y jump from row to row. CSC is the natural format when an algorithm needs whole columns, as many sparse factorization methods do.
The choice between CSR and CSC is about which loop comes first, rows or columns. Both store the same numbers in the same amount of memory.
Choosing a Format
Start with the density. If CSR is smaller than the dense array, which for this matrix size means below about two thirds full, a sparse format saves memory. Then look at speed separately. At 50 percent density CSR used 75 percent of the dense memory and was only twice as fast, so a simple dense array is a reasonable choice for a matrix that full.
Next, match the format to the work. Row-by-row algorithms and the ordinary y = A x product suit CSR, and column-by-column algorithms suit CSC. While a matrix is still being assembled, merged or read from a file, keep it in COO and convert it to CSR or CSC once it is complete. If the structure keeps changing, a hash table keyed by row and column is a flexible way to collect entries before the conversion.
For real test data, the SuiteSparse Matrix Collection offers thousands of matrices from real applications. This article uses generated matrices so the density can be set exactly. In Python, SciPy’s sparse module provides the same three formats.
Implementation in C
The C code keeps one struct per format: COO with row, column and value arrays, CSR with values, column indexes and row pointers, and CSC with values, row indexes and column pointers. A plain dense array serves as the reference for checking every product. The builder below copies the input entries, rejects positions outside the matrix, sorts the entries, and merges repeated positions by adding their values.
bool coo_build(Coo *coo, int n, const Triple *triplets, int count)
{
Triple *sorted = NULL;
int index;
int nnz;
if (coo == NULL)
return false;
coo_clear(coo);
if (n <= 0 || count < 0 || (count > 0 && triplets == NULL))
return false;
if (count == 0) {
coo->n = n;
return true;
}
sorted = malloc((size_t)count * sizeof *sorted);
coo->row = malloc((size_t)count * sizeof *coo->row);
coo->col = malloc((size_t)count * sizeof *coo->col);
coo->val = malloc((size_t)count * sizeof *coo->val);
if (sorted == NULL || coo->row == NULL || coo->col == NULL ||
coo->val == NULL) {
free(sorted);
coo_free(coo);
return false;
}
memcpy(sorted, triplets, (size_t)count * sizeof *sorted);
for (index = 0; index < count; ++index) {
if (sorted[index].row < 0 || sorted[index].row >= n ||
sorted[index].col < 0 || sorted[index].col >= n) {
free(sorted);
coo_free(coo);
return false;
}
}
qsort(sorted, (size_t)count, sizeof *sorted, compare_triples);
nnz = 0;
for (index = 0; index < count; ++index) {
if (nnz > 0 && coo->row[nnz - 1] == sorted[index].row &&
coo->col[nnz - 1] == sorted[index].col) {
coo->val[nnz - 1] += sorted[index].value;
} else {
coo->row[nnz] = sorted[index].row;
coo->col[nnz] = sorted[index].col;
coo->val[nnz] = sorted[index].value;
nnz++;
}
}
free(sorted);
coo->n = n;
coo->nnz = nnz;
coo->row = shrink_block(coo->row, (size_t)nnz * sizeof *coo->row);
coo->col = shrink_block(coo->col, (size_t)nnz * sizeof *coo->col);
coo->val = shrink_block(coo->val, (size_t)nnz * sizeof *coo->val);
return true;
}
The conversion to CSR follows the three steps in the aside above: count the entries per row, turn the counts into running totals, and place each entry.
bool coo_to_csr(const Coo *coo, Csr *csr)
{
int *next = NULL;
int row;
int index;
int nnz;
if (coo == NULL || csr == NULL || coo->n <= 0 || coo->nnz < 0)
return false;
csr_clear(csr);
nnz = coo->nnz;
csr->row_ptr = calloc((size_t)coo->n + 1, sizeof *csr->row_ptr);
if (nnz > 0) {
csr->val = malloc((size_t)nnz * sizeof *csr->val);
csr->col_idx = malloc((size_t)nnz * sizeof *csr->col_idx);
next = malloc((size_t)coo->n * sizeof *next);
}
if (csr->row_ptr == NULL || (nnz > 0 && (csr->val == NULL ||
csr->col_idx == NULL ||
next == NULL))) {
free(next);
csr_free(csr);
return false;
}
for (index = 0; index < nnz; ++index)
csr->row_ptr[coo->row[index] + 1]++;
for (row = 0; row < coo->n; ++row)
csr->row_ptr[row + 1] += csr->row_ptr[row];
if (nnz > 0) {
memcpy(next, csr->row_ptr, (size_t)coo->n * sizeof *next);
for (index = 0; index < nnz; ++index) {
int at = next[coo->row[index]]++;
csr->val[at] = coo->val[index];
csr->col_idx[at] = coo->col[index];
}
free(next);
}
csr->n = coo->n;
csr->nnz = nnz;
return true;
}
The CSR product computes one row sum at a time.
void spmv_csr(const Csr *csr, const double *x, double *y)
{
int row;
for (row = 0; row < csr->n; ++row) {
double sum = 0.0;
int at;
for (at = csr->row_ptr[row]; at < csr->row_ptr[row + 1]; ++at)
sum += csr->val[at] * x[csr->col_idx[at]];
y[row] = sum;
}
}
The demo builds the 4 by 4 matrix from Figure 1, prints all three formats, and multiplies by a vector of ones. Each value of y is the sum of one row.
sparse matrix: COO, CSR and CSC
matrix 4x4, nnz 5
COO rows: 0 0 1 2 3
COO cols: 0 3 1 2 3
COO vals: 1.50 5.50 2.50 3.50 4.50
CSR row_ptr: 0 2 3 4 5
CSR col_idx: 0 3 1 2 3
CSR values: 1.50 5.50 2.50 3.50 4.50
CSC col_ptr: 0 1 2 3 5
CSC row_idx: 0 1 2 0 3
CSC values: 1.50 2.50 3.50 5.50 4.50
y = A*x, x all ones: 7.00 2.50 3.50 4.50
max diff dense vs COO/CSR/CSC: 0.000000
Measured: Memory Against Dense
The memory experiment builds every format from the same generated matrix at each density and reports the bytes each one allocates. It also checks the byte counts against the formulas from the definition section, so a size that disagrees with the arithmetic stops the program.
static void run_row(const Density *density)
{
int count = target_count(density->permille);
Triple *triplets = malloc((size_t)count * sizeof *triplets);
Coo coo;
Csr csr;
Csc csc;
size_t dense_size;
size_t coo_size;
size_t csr_size;
size_t csc_size;
double ratio;
if (triplets == NULL)
fail("out of memory for the triplet list");
if (!generate_triplets(triplets, count))
fail("out of memory for the coordinate bitmap");
if (!coo_build(&coo, N, triplets, count))
fail("the COO build failed");
free(triplets);
if (!coo_to_csr(&coo, &csr))
fail("the COO to CSR conversion failed");
if (!coo_to_csc(&coo, &csc))
fail("the COO to CSC conversion failed");
if (coo.nnz != count || csr.nnz != count || csc.nnz != count)
fail("the sampled coordinates were not unique");
dense_size = dense_bytes(N);
coo_size = coo_bytes(&coo);
csr_size = csr_bytes(&csr);
csc_size = csc_bytes(&csc);
if (dense_size != (size_t)N * (size_t)N * sizeof(double) ||
coo_size != (size_t)coo.nnz * (2 * sizeof(int) + sizeof(double)) ||
csr_size != (size_t)csr.nnz * (sizeof(double) + sizeof(int)) +
((size_t)N + 1) * sizeof(int) ||
csc_size != (size_t)csc.nnz * (sizeof(double) + sizeof(int)) +
((size_t)N + 1) * sizeof(int))
fail("a byte count disagrees with the array arithmetic");
if (csr_size >= dense_size && density->permille <= 100)
fail("CSR is not smaller than dense at 1 or 10 percent density");
ratio = (double)csr_size / (double)dense_size;
printf("%-9s%-9d%-13zu%-11zu%-11zu%-11zu%.3f\n", density->label, count,
dense_size, coo_size, csr_size, csc_size, ratio);
csc_free(&csc);
csr_free(&csr);
coo_free(&coo);
}
int main(void)
{
int row;
printf("matrix %dx%d, entries %d, dense bytes %zu\n", N, N, CELLS,
dense_bytes(N));
printf("%-9s%-9s%-13s%-11s%-11s%-11s%s\n", "density", "nnz", "dense_bytes",
"coo_bytes", "csr_bytes", "csc_bytes", "csr_vs_dense");
for (row = 0; row < DENSITY_ROWS; ++row)
run_row(&DENSITIES[row]);
return EXIT_SUCCESS;
}
Output:
matrix 1024x1024, entries 1048576, dense bytes 8388608
density nnz dense_bytes coo_bytes csr_bytes csc_bytes csr_vs_dense
1% 10486 8388608 167776 129932 129932 0.015
10% 104858 8388608 1677728 1262396 1262396 0.150
50% 524288 8388608 8388608 6295556 6295556 0.750
The measured sizes match the formulas exactly. The dense array is 8,388,608 bytes at every density. CSR and CSC need 129,932 bytes at 1 percent, 0.015 of the dense size, then 1,262,396 bytes at 10 percent (0.150) and 6,295,556 bytes at 50 percent (0.750).
COO needs 16 bytes per nonzero, so it takes 167,776 bytes at 1 percent and 1,677,728 at 10 percent. At 50 percent it takes exactly 8,388,608 bytes, the same as the dense array, because 16 bytes times half the cells equals 8 bytes times all of them. CSR stays smaller than the dense array up to 698,709 nonzeros, which is 66.6 percent of the cells.
Measured: Matrix-Vector Multiply Time
The timing experiment first checks that every sparse product matches the dense product, and then times 100 products in each format.
static double time_products(int format, const Coo *coo, const Csr *csr,
const Csc *csc, const double *dense,
const double *x, double *y)
{
double started;
double elapsed;
int run;
started = now_ms();
for (run = 0; run < RUNS; ++run) {
switch (format) {
case 0:
spmv_dense(dense, N, x, y);
break;
case 1:
spmv_coo(coo, x, y);
break;
case 2:
spmv_csr(csr, x, y);
break;
default:
spmv_csc(csc, x, y);
break;
}
}
elapsed = now_ms() - started;
return elapsed;
}
static void run_row(const Density *density, double *differences_out)
{
int count = target_count(density->permille);
Triple *triplets = malloc((size_t)count * sizeof *triplets);
double *dense = malloc((size_t)CELLS * sizeof *dense);
double *x = malloc((size_t)N * sizeof *x);
double *y_dense = malloc((size_t)N * sizeof *y_dense);
double *y_coo = malloc((size_t)N * sizeof *y_coo);
double *y_csr = malloc((size_t)N * sizeof *y_csr);
double *y_csc = malloc((size_t)N * sizeof *y_csc);
Coo coo;
Csr csr;
Csc csc;
double dense_ms;
double coo_ms;
double csr_ms;
double csc_ms;
double speedup;
double difference;
int index;
if (triplets == NULL || dense == NULL || x == NULL || y_dense == NULL ||
y_coo == NULL || y_csr == NULL || y_csc == NULL)
fail("out of memory for the matrix and the vectors");
if (!generate_triplets(triplets, count))
fail("out of memory for the coordinate bitmap");
if (!coo_build(&coo, N, triplets, count))
fail("the COO build failed");
free(triplets);
if (!coo_to_csr(&coo, &csr))
fail("the COO to CSR conversion failed");
if (!coo_to_csc(&coo, &csc))
fail("the COO to CSC conversion failed");
if (coo.nnz != count || csr.nnz != count || csc.nnz != count)
fail("the sampled coordinates were not unique");
coo_to_dense(&coo, dense);
for (index = 0; index < N; ++index)
x[index] = (double)(index % 7 - 3) * 0.5;
/* Check every format against the dense product before timing it. */
spmv_dense(dense, N, x, y_dense);
spmv_coo(&coo, x, y_coo);
spmv_csr(&csr, x, y_csr);
spmv_csc(&csc, x, y_csc);
difference = max_abs_diff(y_dense, y_coo, N);
if (max_abs_diff(y_dense, y_csr, N) > difference)
difference = max_abs_diff(y_dense, y_csr, N);
if (max_abs_diff(y_dense, y_csc, N) > difference)
difference = max_abs_diff(y_dense, y_csc, N);
if (difference > DIFFERENCE_LIMIT)
fail("a sparse product disagrees with the dense one");
dense_ms = time_products(0, &coo, &csr, &csc, dense, x, y_dense);
coo_ms = time_products(1, &coo, &csr, &csc, dense, x, y_coo);
csr_ms = time_products(2, &coo, &csr, &csc, dense, x, y_csr);
csc_ms = time_products(3, &coo, &csr, &csc, dense, x, y_csc);
result_sink = checksum(y_dense) + checksum(y_coo) + checksum(y_csr) +
checksum(y_csc);
speedup = csr_ms > 0.0 ? dense_ms / csr_ms : 0.0;
printf("%-9s%-9d%-10.3f%-8.3f%-8.3f%-8.3f%.2f\n", density->label, count,
dense_ms, coo_ms, csr_ms, csc_ms, speedup);
*differences_out = difference;
csc_free(&csc);
csr_free(&csr);
coo_free(&coo);
free(y_csc);
free(y_csr);
free(y_coo);
free(y_dense);
free(x);
free(dense);
}
Output:
matrix 1024x1024, 100 matrix-vector products per format
density nnz dense_ms coo_ms csr_ms csc_ms csr_speedup
1% 10486 108.188 1.789 1.023 0.930 105.79
10% 104858 105.216 22.348 9.304 7.648 11.31
50% 524288 107.263 123.282 53.822 32.740 1.99
max diff vs dense, 1%: 0.000000
max diff vs dense, 10%: 0.000000
max diff vs dense, 50%: 0.000000
The dense product took between 105 and 108 milliseconds at every density, because it always multiplies all 1,048,576 cells, zeros included. The sparse products only touch the nonzeros. At 1 percent, CSR took 1.023 milliseconds, 105.79 times faster than dense. At 10 percent it took 9.304 milliseconds, 11.31 times faster. At 50 percent the gap nearly closed: CSR took 53.822 milliseconds, only 1.99 times faster, and COO took 123.282 milliseconds, slower than the dense loop.
On this machine CSC was faster than CSR at all three densities: 0.930, 7.648 and 32.740 milliseconds. That ordering did not hold elsewhere. On a second Linux machine, a shared cloud server running the GCC build, CSR was faster at 1 and 10 percent and the two tied at 50 percent.
A likely cause is the processor’s ability to overlap work. CSR adds each row into one running sum, so every addition waits for the previous one, while CSC’s additions go to different rows and can overlap. How much that matters depends on the processor. Treat CSR and CSC as equally fast for this product, and choose between them by access pattern.
Five Ways a Sparse Matrix Implementation Passes a Quick Test and Still Fails
Each program below compiles without warnings and prints believable output until a wrong value appears or the sanitizer stops it. The first is caught by AddressSanitizer. The other four print a wrong result next to the correct one.
1. A Row Pointer Array One Entry Too Short
static void build_csr(int *col_idx, double *val)
{
int counts[N] = {0};
int next[N];
volatile int entries = ROW_PTR_ENTRIES;
int *row_ptr = malloc((size_t)entries * sizeof *row_ptr);
int index;
if (row_ptr == NULL)
fail("out of memory for row_ptr");
for (index = 0; index < NNZ; ++index)
counts[COO_ROW[index]]++;
row_ptr[0] = 0;
for (index = 0; index < N; ++index)
row_ptr[index + 1] = row_ptr[index] + counts[index];
for (index = 0; index < N; ++index)
next[index] = row_ptr[index];
for (index = 0; index < NNZ; ++index) {
int at = next[COO_ROW[index]]++;
val[at] = COO_VAL[index];
col_idx[at] = COO_COL[index];
}
free(row_ptr);
}
int main(void)
{
int col_idx[NNZ];
double val[NNZ];
setvbuf(stdout, NULL, _IONBF, 0);
puts("csr_row_ptr_short: a 4x4 matrix with 5 entries has row_ptr 0 2 3 4 5");
puts("row_ptr needs n + 1 = 5 entries: one per row plus the row after the last");
puts("the builder allocates row_ptr[4] and the prefix sum writes row_ptr[4], one past the array");
puts("building the CSR now");
build_csr(col_idx, val);
puts("the write past the array did not fail loudly");
return EXIT_SUCCESS;
}
Output:
csr_row_ptr_short: a 4x4 matrix with 5 entries has row_ptr 0 2 3 4 5
row_ptr needs n + 1 = 5 entries: one per row plus the row after the last
the builder allocates row_ptr[4] and the prefix sum writes row_ptr[4], one past the array
building the CSR now
AddressSanitizer then stops the program inside the builder. Its report, summarized:
ERROR: AddressSanitizer: heap-buffer-overflow
WRITE of size 4, 0 bytes after a 16-byte heap region
SUMMARY: AddressSanitizer: heap-buffer-overflow pitfalls/csr_row_ptr_short.c:59 in build_csr
The row pointer array needs n + 1 entries, because each row’s end is the next row’s start, and the last row needs an end too. The broken builder allocates only n entries. The running-total loop then writes row_ptr[n], one element past the end of the array, and AddressSanitizer reports a 4-byte heap-buffer-overflow write in the builder. Without the sanitizer, the write lands in whatever memory follows the array and may go unnoticed. The fix is to allocate n + 1 entries.
2. A Row Loop That Skips Each Row’s First Entry
static void spmv_off_by_one(const double *val, const int *col_idx,
const int *row_ptr, const double *x, double *y)
{
int row;
for (row = 0; row < N; ++row) {
double sum = 0.0;
int at;
for (at = row_ptr[row] + 1; at < row_ptr[row + 1]; ++at)
sum += val[at] * x[col_idx[at]];
y[row] = sum;
}
}
/* The same product with the row slice starting at row_ptr[row]. */
static void spmv_correct(const double *val, const int *col_idx,
const int *row_ptr, const double *x, double *y)
{
int row;
for (row = 0; row < N; ++row) {
double sum = 0.0;
int at;
for (at = row_ptr[row]; at < row_ptr[row + 1]; ++at)
sum += val[at] * x[col_idx[at]];
y[row] = sum;
}
}
int main(void)
{
int row_ptr[N + 1];
int col_idx[NNZ];
double val[NNZ];
double x[N] = {1.0, 1.0, 1.0, 1.0};
double wrong[N];
double correct[N];
build_csr(row_ptr, col_idx, val);
spmv_off_by_one(val, col_idx, row_ptr, x, wrong);
spmv_correct(val, col_idx, row_ptr, x, correct);
puts("csr_loop_off_by_one: the row loop starts at row_ptr[row] + 1");
print_y("wrong y:", wrong);
print_y("correct y:", correct);
return 0;
}
Output:
csr_loop_off_by_one: the row loop starts at row_ptr[row] + 1
wrong y: 5.50 0.00 0.00 0.00
correct y: 7.00 2.50 3.50 4.50
The broken loop starts each row at row_ptr[row] + 1 instead of row_ptr[row], so it skips the first entry of every row. Row 0 loses its 1.50 and keeps only 5.50. Rows 1 to 3 have one entry each, so they lose everything and become 0.00. The correct result is 7.00, 2.50, 3.50 and 4.50. An off-by-one at the start of a row range is just as wrong as one at the end.
3. Duplicate Coordinates That Are Not Summed
static int build_coo_buggy(int *row, int *col, double *val)
{
int index;
for (index = 0; index < TRIPLET_COUNT; ++index) {
row[index] = TRIPLETS[index].row;
col[index] = TRIPLETS[index].col;
val[index] = TRIPLETS[index].value;
}
return TRIPLET_COUNT;
}
static int build_coo_correct(int *row, int *col, double *val)
{
Triple sorted[TRIPLET_COUNT];
int nnz = 0;
int index;
int at;
for (index = 0; index < TRIPLET_COUNT; ++index) {
Triple key = TRIPLETS[index];
at = index;
while (at > 0 && (sorted[at - 1].row > key.row ||
(sorted[at - 1].row == key.row &&
sorted[at - 1].col > key.col))) {
sorted[at] = sorted[at - 1];
at--;
}
sorted[at] = key;
}
for (index = 0; index < TRIPLET_COUNT; ++index) {
if (nnz > 0 && row[nnz - 1] == sorted[index].row &&
col[nnz - 1] == sorted[index].col) {
val[nnz - 1] += sorted[index].value;
} else {
row[nnz] = sorted[index].row;
col[nnz] = sorted[index].col;
val[nnz] = sorted[index].value;
nnz++;
}
}
return nnz;
}
int main(void)
{
int row[TRIPLET_COUNT];
int col[TRIPLET_COUNT];
double val[TRIPLET_COUNT];
double dense[N * N];
double x[N] = {1.0, 1.0, 1.0, 1.0};
double wrong[N];
double expected[N];
int buggy_nnz;
int correct_nnz;
buggy_nnz = build_coo_buggy(row, col, val);
coo_to_dense(row, col, val, buggy_nnz, dense);
spmv_dense(dense, x, wrong);
correct_nnz = build_coo_correct(row, col, val);
coo_to_dense(row, col, val, correct_nnz, dense);
spmv_dense(dense, x, expected);
puts("coo_duplicates_not_summed: the builder keeps the repeated cell (0,0) "
"as two entries");
printf("buggy nnz %d, expected nnz %d\n", buggy_nnz, correct_nnz);
print_y("wrong y:", wrong);
print_y("expected y:", expected);
return 0;
}
Output:
coo_duplicates_not_summed: the builder keeps the repeated cell (0,0) as two entries
buggy nnz 6, expected nnz 5
wrong y: 6.50 2.50 3.50 4.50
expected y: 7.00 2.50 3.50 4.50
The input lists cell (0, 0) twice, first with 0.5 and later with 1.0, so the intended value is 1.5. The buggy builder keeps both entries, which makes the nonzero count 6 instead of 5. The conversion to a dense array then assigns each entry to its cell, so the later 1.0 overwrites the 0.5. Row 0 sums to 6.50 instead of 7.00. A product that added every COO entry directly would get 7.00, which is why this bug can hide. It only appears when later code assumes each cell occurs once.
4. A CSC Product That Writes to the Column Instead of the Row
static void spmv_column_as_row(const double *val, const int *row_idx,
const int *col_ptr, const double *x, double *y)
{
int col;
for (col = 0; col < N; ++col)
y[col] = 0.0;
for (col = 0; col < N; ++col) {
int at;
for (at = col_ptr[col]; at < col_ptr[col + 1]; ++at)
y[col] += val[at] * x[row_idx[at]];
}
}
/* The same product writing each contribution to its stored row. */
static void spmv_correct(const double *val, const int *row_idx,
const int *col_ptr, const double *x, double *y)
{
int col;
for (col = 0; col < N; ++col)
y[col] = 0.0;
for (col = 0; col < N; ++col) {
int at;
for (at = col_ptr[col]; at < col_ptr[col + 1]; ++at)
y[row_idx[at]] += val[at] * x[col];
}
}
int main(void)
{
int col_ptr[N + 1];
int row_idx[NNZ];
double val[NNZ];
double x[N] = {1.0, 1.0, 1.0, 1.0};
double wrong[N];
double correct[N];
build_csc(col_ptr, row_idx, val);
spmv_column_as_row(val, row_idx, col_ptr, x, wrong);
spmv_correct(val, row_idx, col_ptr, x, correct);
puts("csc_column_as_row: the CSC product writes y[col] instead of "
"y[row_idx[at]]");
print_y("wrong y:", wrong);
print_y("correct y:", correct);
return 0;
}
Output:
csc_column_as_row: the CSC product writes y[col] instead of y[row_idx[at]]
wrong y: 1.50 2.50 3.50 10.00
correct y: 7.00 2.50 3.50 4.50
In CSC, each value’s row index says which element of y it belongs to. The broken loop adds the value to y[col], the column being walked, instead of y[row_idx[at]]. The result is 1.50, 2.50, 3.50 and 10.00, because column 3 holds 5.5 and 4.5. The correct result is 7.00, 2.50, 3.50 and 4.50. Both results add up to 17.50, so a test that only checks the total of y will pass. The broken loop has in fact computed the product with the transposed matrix.
5. A Dense Baseline Indexed Column-Major
static void spmv_column_major(const double *dense, const double *x, double *y)
{
int row;
for (row = 0; row < N; ++row) {
double sum = 0.0;
int col;
for (col = 0; col < N; ++col)
sum += dense[col * N + row] * x[col];
y[row] = sum;
}
}
/* The same product reading the cell at row * n + col. */
static void spmv_row_major(const double *dense, const double *x, double *y)
{
int row;
for (row = 0; row < N; ++row) {
double sum = 0.0;
int col;
for (col = 0; col < N; ++col)
sum += dense[row * N + col] * x[col];
y[row] = sum;
}
}
int main(void)
{
double dense[N * N];
double x[N] = {1.0, 1.0, 1.0, 1.0};
double wrong[N];
double correct[N];
build_dense(dense);
spmv_column_major(dense, x, wrong);
spmv_row_major(dense, x, correct);
puts("dense_column_major_index: the dense baseline indexes a[col * n + row]");
print_y("wrong y:", wrong);
print_y("row-major y:", correct);
return 0;
}
Output:
dense_column_major_index: the dense baseline indexes a[col * n + row]
wrong y: 1.50 2.50 3.50 10.00
row-major y: 7.00 2.50 3.50 4.50
A dense matrix stored row by row keeps cell (row, col) at index row × n + col. The broken baseline reads index col × n + row, which is the cell of the transposed matrix, so it also multiplies by the transpose and prints the same wrong result as the fourth pitfall. A bug in the reference is the most dangerous kind. If every sparse product is checked against a transposed baseline, the correct sparse code fails its tests, and a sparse product with the same mistake passes.
Key Takeaways
- A sparse matrix stores only its nonzero values and their positions. COO stores a row, column and value for each, CSR groups them by row, and CSC groups them by column.
- In C, with 4-byte indexes and 8-byte values, COO costs 16 bytes per nonzero, CSR and CSC cost 12 bytes per nonzero plus 4 bytes per row or column, and a dense matrix costs 8 bytes per cell.
- For a 1024 by 1024 matrix, CSR is smaller than the dense array up to 66.6 percent density. It was 0.015 of the dense size at 1 percent and 0.750 at 50 percent.
- CSR’s product was 105.79 times faster than dense at 1 percent, 11.31 times at 10 percent and only 1.99 times at 50 percent, where COO was slower than dense.
- CSR and CSC store the same data in the same space. Which one multiplies faster depended on the machine, so choose by access pattern.
- Build in COO, sum duplicate positions, convert once, and give the pointer array n + 1 entries.
Frequently Asked Questions
Conclusion
The three formats hold the same matrix and differ only in how they record positions, and that choice decides both memory and speed. COO is the easiest to build and the slowest to multiply. CSR makes the row-by-row product a sequential scan, and CSC does the same for columns. The memory followed the formulas exactly: CSR took 0.015 of the dense size at 1 percent density, 0.150 at 10 percent and 0.750 at 50 percent, and COO matched the dense size at 50 percent. The CSR product was 105.79 times faster than dense at 1 percent and only 1.99 times faster at 50 percent.
The data structures hub lists the other structures in this series. In your own code, choose the format by access pattern first and memory second, and switch to a library once matrices grow large. Keep the pointer and index arithmetic under test, because the pitfalls show how a short pointer array or a swapped index turns a correct format into a wrong answer.
Source Code and Tests
The programs on this page are in the data-structures/sparse-matrix directory of the MYCPLUS C examples repository:
| Language | Repository directory | Build status |
|---|---|---|
| C | mycplus/c-examples: data-structures/sparse-matrix |
The examples build and test with CMake:
cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure
The demo’s output is compared byte for byte with tests/expected/ordered.txt. The tests compare all three formats with the dense matrix on fixed and random matrices. They check that duplicates are summed, that every pointer array starts at 0, never decreases and ends at the nonzero count, and that all three products match the dense product. They also check the fixed parts of both experiments’ output. The workflow runs the tests and pitfalls under AddressSanitizer and UndefinedBehaviorSanitizer, and the short pointer array pitfall must produce its sanitizer summary. No test checks a time.
What I Verified
The example directory contains the test programs and the captured runs. The table states which system ran each check.
| Check | Ubuntu 24.04 (WSL2) | Windows 11 (MSVC) |
|---|---|---|
| Build and tests, GCC 13.3, C11 and C17 | Pass (16 of 16 tests) | Not applicable |
| Build and tests, Clang 18.1.3, C11 and C17 | Pass (16 of 16 tests) | Not applicable |
Build and tests, MSVC 19.44 /W4 /WX | Not applicable | Pass (16 of 16 tests) |
| AddressSanitizer and UndefinedBehaviorSanitizer, tests, demo and pitfalls | Pass (16 of 16 tests) | Not applicable |
| Five pitfalls, each caught by its check or sanitizer summary | Pass (4 output checks, 1 AddressSanitizer summary) | Not applicable |
| Memory and timing experiments | Run, output above | Not run |
| Independent rerun on a second Linux x86-64 machine (GCC 13.3, Clang 18.1.3) | Pass (16 of 16 tests with both compilers and under the sanitizers, demo, memory table and four pitfall outputs identical to the captures, timing shape repeated) | Not applicable |
Not covered: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, macOS, other densities and matrix shapes, multithreaded products, and timings on other machines beyond the one rerun noted above.




