Accessing elements using [row][col]
What you'll learn: How to use two sets of square brackets to pinpoint a specific value within a 2D array.
The Grid Coordinate System
Think of a 2D array like a theater seating chart or a spreadsheet. To find a specific seat, you can’t just say "Seat 5." You need two pieces of information: the row number and the seat number within that row.
In C, we access these "cells" by placing two sets of square brackets next to the array name. The first set of brackets selects the row, and the second set selects the column. It looks like this: arrayName[rowIndex][columnIndex].
Zero-indexed counting
Just like standard 1D arrays, 2D arrays in C start counting at zero.
- The very first row is
0. - The very first column is
0.
If you have a 3x3 grid, the rows are numbered 0, 1, and 2. The columns are also numbered 0, 1, and 2. If you try to access [3][3], you are looking for the fourth row and fourth column, which doesn't exist, leading to a crash or "garbage" data.
Seeing it in code
Imagine we have a small grid of scores. We want to pull out a specific score located in the second row, third column.
#include <stdio.h>
int main() {
// A 2D array with 2 rows and 3 columns
int scores[2][3] = {
{85, 92, 78}, // Row 0
{90, 88, 95} // Row 1
};
// Accessing the element at Row 1, Column 2
// Remember: Row 1 is the second row, Column 2 is the third column
int myScore = scores[1][2];
printf("The value is: %d", myScore); // Outputs 95
return 0;
}
How the computer finds it
When you write scores[1][2], the computer does a little mental math. It jumps to the start of the second row (skipping all the items in the first row) and then moves two steps forward within that row to find the exact integer you asked for. Because this happens instantly, you can read from or write to any "cell" in the grid just as easily as a single variable.
Key takeaway
To access a 2D array element, use array[row][col], remembering that both indices start counting at zero.