🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Two Dimensional Arrays in C
Understand rows, columns and row-major memory layout, and learn to count and address every element of a 2D array. A practical free C tutorial for embedded C programming.
Two dimensional arrays in C let you store grid-shaped data: a keypad, an LED matrix, a block of sensor readings or a tiny image. In this lecture of our free C programming course you will learn how to declare a 2D array, how the two subscripts map to rows and columns, and, most importantly, how the compiler lays the grid out in memory. That last detail is what makes C programming for embedded systems predictable: once you know the layout you can reason about RAM usage, DMA transfers and display buffers with confidence.
What You Will Learn
- The declaration syntax for a two dimensional array and what each subscript means
- How to find the first and last valid index of a grid
- Row-major layout: how rows and columns become a flat run of bytes
- Counting rows, columns and total bytes with
sizeof - Where 2D arrays appear in real embedded projects
Prerequisites
- One-dimensional arrays: declaration, indexing and looping (earlier lectures)
- Nested
forloops from the Control Statements chapter - GCC installed so you can run the demo
Declaring Two Dimensional Arrays in C
A one-dimensional array is a row of boxes. A two dimensional array is a table of boxes, so it needs two numbers to describe its shape: how many rows, and how many columns in each row. The general form is:
element_type name[ROWS][COLUMNS];
For example, uint16_t grid[3][4]; creates a table with 3 rows and 4 columns, holding 3 × 4 = 12 elements of 16 bits each. You read the declaration left to right: the first bracket is the row count, the second is the column count.
Reading and Writing a Single Element
To reach one element you give two subscripts, row first and column second: grid[2][3] is the element in row 2, column 3. Indexing starts at zero in both directions, so the first element is grid[0][0] and the last is grid[2][3], which is row count minus one and column count minus one.
How a 2D Array Sits in Memory
RAM has no rows and columns; it is one long line of bytes. C stores a two dimensional array in row-major order: the entire first row comes first, then the entire second row, and so on, with no gaps. Moving along a row means stepping to the next neighbouring element. Moving down a column means jumping over an entire row.
The byte offset of element [r][c] from the start follows a simple formula, where COLS is the number of columns and size is the byte size of one element:
offset = (r * COLS + c) * size
That formula is exactly what the compiler generates for you whenever you write grid[r][c]. It also explains why the column count matters so much to the compiler, while the row count does not enter the formula at all. We will return to that fact when we pass 2D arrays to functions.
Free C Tutorial: Inspect a 2D Array Layout
Rather than trust the formula, let the program prove it. The demo fills a 3 by 4 array, prints its dimensions using sizeof, and then prints the byte offset of every element.
#include <stdio.h>
#include <stdint.h>
int main(void)
{
uint16_t grid[3][4];
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 4; c++) {
grid[r][c] = (uint16_t)(r * 10 + c);
}
}
size_t rows = sizeof grid / sizeof grid[0];
size_t cols = sizeof grid[0] / sizeof grid[0][0];
printf("total bytes = %zu, rows = %zu, cols = %zu, elements = %zu\n",
sizeof grid, rows, cols, rows * cols);
const unsigned char *base = (const unsigned char *)&grid[0][0];
printf("byte offset of each element from grid[0][0]:\n");
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 4; c++) {
printf("%3td ", (const unsigned char *)&grid[r][c] - base);
}
printf("\n");
}
printf("grid[2][3] = %u\n", grid[2][3]);
return 0;
}
gcc -std=c17 -Wall -Wextra -Wpedantic -o grid_basics grid_basics.c
./grid_basics
Expected output:
total bytes = 24, rows = 3, cols = 4, elements = 12
byte offset of each element from grid[0][0]:
0 2 4 6
8 10 12 14
16 18 20 22
grid[2][3] = 23
What the Output Tells You
- 24 bytes total: 12 elements times 2 bytes each, with no hidden padding between rows.
- rows = sizeof grid / sizeof grid[0]:
grid[0]is one whole row (8 bytes), so 24 divided by 8 gives 3 rows. - cols = sizeof grid[0] / sizeof grid[0][0]: one row (8 bytes) divided by one element (2 bytes) gives 4 columns.
- Offsets grow by 2 along a row, and the start of each new row picks up exactly where the previous row ended: 6 then 8, 14 then 16.
- grid[2][3] = 23 because the fill formula was
r * 10 + c, so row 2, column 3 holds 2 × 10 + 3.
Dimensions at a Glance
| Question | Expression | Result for grid[3][4] of uint16_t |
|---|---|---|
| Total size in bytes | sizeof grid | 24 |
| Number of rows | sizeof grid / sizeof grid[0] | 3 |
| Number of columns | sizeof grid[0] / sizeof grid[0][0] | 4 |
| First element | grid[0][0] | Offset 0 |
| Last element | grid[2][3] | Offset 22 |
Where 2D Arrays Appear in Embedded C Programming
- Matrix keypads: a 4 by 4 key map turns a scanned row and column into a character.
- LED matrices: an 8 by 8 array of on/off values mirrors the physical grid you refresh.
- Display buffers: small OLED screens are often driven from a page-by-column byte buffer.
- Sensor grids: thermal cameras and multi-room temperature loggers produce rows of readings.
- Lookup tables: a two-input calibration or gamma table indexed by two values.
Common Mistakes and Troubleshooting
| Mistake | Symptom | Fix |
|---|---|---|
| Swapping row and column indices | Image appears flipped or transposed, wrong key returned | Always write row first, column second |
Off-by-one: using grid[3][4] in a 3 by 4 array | Reads memory beyond the array | Valid indices stop at size minus one |
Writing grid[1, 2] instead of grid[1][2] | Compiles, but the comma operator reduces it to grid[2] | Use one pair of brackets per dimension |
| Assuming a column index beyond the width wraps to the next row | Undefined behaviour; compilers may warn or optimise it away | Keep every index inside its own dimension |
| Forgetting RAM cost | Linker error: region RAM overflowed | Multiply rows by columns by element size before declaring |
Best Practices, Performance and Security
Best Practices
- Define row and column counts with named constants so loops and declarations stay in sync.
- Pick the element type deliberately:
uint8_tfor flags,uint16_tfor ADC data. - Comment which index is the row and which is the column when the meaning is not obvious.
Performance Considerations
Because storage is row-major, looping with the row index on the outside and the column index on the inside visits memory in order. That is friendly to caches on larger processors and to DMA-style sequential access on microcontrollers. Looping the other way round jumps a whole row at a time and can be noticeably slower on cached CPUs.
Security Considerations
Both indices must be validated whenever they come from outside, such as a key scan result or a protocol field. An unchecked row or column turns a harmless table lookup into an out-of-bounds read or write.
Summary and Key Takeaways
Remember these points
- Declare with
type name[ROWS][COLS]; access with row first, column second. - Indices run from 0 to size minus one in each dimension.
- Memory is row-major: whole rows follow each other with no gaps.
- Offset of
[r][c]is(r * COLS + c) * size. - Rows and columns can be counted with two
sizeofdivisions.
You can now picture a two dimensional array both ways: as a neat table on paper and as a flat strip of bytes in RAM. That double vision is what lets you size buffers correctly and avoid indexing bugs. In the next lecture of this free embedded C course we put the grid to work with nested loops, row and column calculations and a transpose.
Frequently Asked Questions
What is a two dimensional array in C?
It is an array of arrays: a table with a fixed number of rows and columns, accessed with two subscripts such as grid[row][col].
Is the first subscript the row or the column?
The first subscript is the row and the second is the column, both starting from zero.
How is a 2D array stored in memory?
In row-major order: all elements of row 0, then all of row 1, and so on, contiguously and without padding between rows for ordinary element types.
How do I get the number of rows and columns of a 2D array?
Rows are sizeof a / sizeof a[0] and columns are sizeof a[0] / sizeof a[0][0], valid where the array is declared.
Can I use a 2D array on a microcontroller with little RAM?
Yes, but calculate the cost first: rows times columns times element size. Use const for tables that never change so they can stay in flash.
Why does grid[1, 2] compile but behave strangely?
Inside brackets the comma is the comma operator, so the expression becomes grid[2], a whole row, not a single element.
Continue the Free C Programming Course
Run the layout demo, change the dimensions, and predict the offsets before you look. Then process the grid with nested loops in the next free C tutorial lecture.

2 Comments